I want to use jQuery to dynamically enclose all text matching a given regexp with a specific tag. For example:
<div class="content">
<div class="spamcontainer">
Eggs and spam is better than ham and spam.
<img src="spam-and-eggs.jpg">
I do not like green eggs and spam, though.
</div>
</div>
If my regexp is ham|spam
and I want to enclose with <span class='meat-product'>
then I would want to transform to
<div class="content">
<div class="spamcontainer">
Eggs and <span class='meat-product'>spam</span> is better than <span class='meat-product'>ham</span> and <span class='meat-product'>spam</span>.
<img src="spam-and-eggs.jpg">
I do not like green eggs and <span class='meat-product'>spam</span>, though.
</div>
</div>
Here's my problem. I know how to do this with just text, and with just html:
$("div.content").text(function() {
return $(this).text().replace(/ham|spam/, function(match) {
return '<span class="meat-product">' + match + '</span>';
});
});
and
$("div.content").html(function(_, html) {
return html.replace(/ham|spam/, function(match) {
return '<span class="meat-product">' + match + '</span>';
});
});
but the former replaces text with text (so I get the text <span ...
instead of a <span>
element), and the latter matches ham
and spam
inside any HTML rather than in just text.
How can I match only text, but also be able to replace that text with HTML elements?