user6428096 user6428096 - 5 months ago 26
jQuery Question

Make some text bold AND some italic

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) {
// http://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 + '>';

// http://stackoverflow.com/a/298758
$(this).contents().each(function() {
if (this.nodeType === 3) //Node.TEXT_NODE
{
// http://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>




Answer

The way it was implemented prevents you from changing multiple tags in a sequence because the element's content was converted into text.

Here's what I have done:

// stips out tags, which causes issues when onverting 2 tags
// return $(this).text().replace(regex, replacement);
// use the html contents of the element
return $(this).html().replace(regex, replacement);

How it's run:

$('p').wrapInTag({
  tag: 'em',
  words: ['world', 'red']
});

$('p').wrapInTag({
  tag: 'strong',
  words: ['is']
});

See the working version here: http://jsbin.com/xamisohehi/edit?html,js,output

Comments