Here’s a bit of code which allows you to highlight any text within any specified container. I’m not sure of a practical application for this; it’s just a bit of fun. If you’re thinking that you can highlight search keywords then don’t use this! That kind of functionality should really be handled on the server-side.
The Code:
function highlight(container,what,spanClass) { var content = container.innerHTML, pattern = new RegExp('(>[^<.]*)(' + what + ')([^<.]*)','g'), replaceWith = '$1<span ' + ( spanClass ? 'class="' + spanClass + '"' : '' ) + '">$2</span>$3', highlighted = content.replace(pattern,replaceWith); return (container.innerHTML = highlighted) !== content; } |
You can specify the container, the word to be searched for, and the class to be given to the wrapping span (e.g. ‘highlight’).
Usage:
highlight(document.getElementById('content'),'hello','highlight'); // This will return false if the word was not found... |
jQuery version:
$.fn.highlight = function(what,spanClass) { return this.each(function(){ var container = this, content = container.innerHTML, pattern = new RegExp('(>[^<.]*)(' + what + ')([^<.]*)','g'), replaceWith = '$1<span ' + ( spanClass ? 'class="' + spanClass + '"' : '' ) + '">$2</span>$3', highlighted = content.replace(pattern,replaceWith); container.innerHTML = highlighted; }); } |
Usage:
$('#content').highlight('hello','highlight'); |
Note: Don’t set the container as a parent of any SCRIPT tags. So, if your body
contains any script tags, don’t set the body as the container.
Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!
Nice tip 🙂
Will keep it in mind.
Cool thanks 🙂
James,
A worthy idea, but there are always edge cases that either don’t work, or are a bit finicky with regular expressions. Having recently written a highlighting script, ensured to work across all A-grade browsers (yup, that includes IE6), there is only one perfect way to accomplish this without poking around in the dark for those edge cases.
Walk the DOM tree looking for textNodes, then using doing a simple indexOf on the content of a textNode. jQuery makes this obscenely easy:
Then use this .textNodes method on containers:
You’ll have to fill in the gaps for some of those external methods and variables (like
found
andwrap_topic
, but a it should not be difficult to do this.Of course, that
textNodes
refers to this:This is how you extract all of the textNodes in a container into a simple array.
Wow Robert! Awesome stuff! My regex attempt was just for a little bit of fun, and to learn a bit, I didn’t think it was a particularly solid implementation. Yours looks superb, thanks for commenting! 🙂
Hi
I want to search for style=”color:#0000FF;” in the source code and replace it with class=”0000FF”
Is this possible to do.
Thanks