I'm getting every text node on the page that contains "em"
I'm then replacing the html (i.e. the text) of the parent of the text node with new HTML.
Try the below code on your console. It should highlight all "em" text on the current page.
But it doesn't. It messes up the whole page instead. What am I doing wrong?
I thought :contains looks for text nodes, not HTML.
var someString = "em";
$(':contains("' + someString + '")').each(function ()
{
var oldHTML = $(this).html();
var regex = new RegExp(someString, "g");
var newHTML = oldHTML.replace(regex, '<span style="background-color: yellow;">' + someString + '</span>');
$(this).html(newHTML);
});
I'm sorry I couldn't find a more intuitive title for my weird problem - please feel free to change it if you can! :)
Thanks!
EDIT :
It turns out my .replace(...)
is also replacing html tags, not just plain text.
I should've been doing something like (although I'm not sure it's the right regex) :
var regex = new RegExp("<.*>(" + someString + ")\/.*>", "g");
var newHTML = oldHTML.replace(regex, '<span style="background-color: yellow;">' + someString + '</span>');