To do something like this, you would have to loop through all the text nodes in the document, find the word, and wrap it.
Something like that:
function highlight(str,node) {
if( !node) node = document.body;
var c = node.children, l = c.length, i, p;
for( i=0; i<l; i++) {
if( c[i].nodeType == 1) highlight(str,c[i]);
if( c[i].nodeType == 3) {
if( (p=c[i].data.indexOf(str)) > -1) {
c[i].splitText(p);
c[i].nextSibling.deleteData(0,str.length);
c[i].parentNode.insertBefore(
document.createElement('b'),c[i].nextSibling
).appendChild(document.createTextNode(str));
}
}
}
}
This should do it. To use, just call highlight("message")
, with whatever text you want. Note that this will be case sensitive - if you require a match without content, let me know and I'll edit to take that into account (although for the most part you could probably get away with highlight("message"); highlight("Message");
)
In addition, you can restrict your search to a specific item. Let's say you have <div id="replace-me">
, you can limit your search to such an element like this:
highlight("message",document.getElementById('replace-me'));
(You can use any way to get node, this is the easiest one)
source
to share