From this question I got the code to find text, wrap it in, and make it bold, which works (I used Jahu's answer, the one with a jsbin). When I copy it to another file and change it to make the text italic, it works.
However, when I put the both of them in the same file (even in different <script>
tags) only the bold one happens. Anyone know why?
$.fn.wrapBoldTag = function(opts) {
// https://stackoverflow.com/a/1646618
function getText(obj) {
return obj.textContent ? obj.textContent : obj.innerText;
}
var tag = opts.tag || 'strong',
words = opts.words || [],
regex = RegExp(words.join('|'), 'gi'),
replacement = '<' + tag + '>$&</' + tag + '>';
// https://stackoverflow.com/a/298758
$(this).contents().each(function() {
if (this.nodeType === 3) //Node.TEXT_NODE
{
// https://stackoverflow.com/a/7698745
$(this).replaceWith(getText(this).replace(regex, replacement));
} else if (!opts.ignoreChildNodes) {
$(this).wrapBoldTag(opts);
}
});
};
$('p').wrapBoldTag({
"words": ["blue"]
});
$('p').wrapBoldTag({
"words": ["edit"],
"ignoreChildNodes": true
});
$.fn.wrapInTag = function(opts) {
var tag = opts.tag || 'strong',
words = opts.words || [],
regex = RegExp(words.join('|'), 'gi'),
replacement = '<' + tag + '>$&</' + tag + '>';
return this.html(function() {
return $(this).text().replace(regex, replacement);
});
};
$('p').wrapInTag({
tag: 'u',
words: ['sky']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>The sky is blue.</p>