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!