jQuery snippet: automatic highlights

A quick jQuery snippet to highlight a specific word. This can just as easily be done with vanilla JavaScript, and if you're not already using jQuery on your site for other reasons that would definitely be a more sensible way to go.

Sometimes you want to highlight a word automagically without having to go through and manually add <span> tags all over the place.

Of course you also want to do this without breaking anything else that has been wrapped in a <p> tag. Ahem, WordPress I'm looking at you.

  • The first line of this iterates over every single <p> tag on the page.
  • The if statement then checks to see whether or not the paragraph in question actually contains the phrase and if it does replaces the sections of it that contain the phrase with the alternative text.

NOTE: if you don't nest the actual replace within a $(this).html(); call what you end up with is just the text being returned and any child elements (e.g. p or img elements being removed from the DOM. This might not bother you if you're working with a site only you are ever likely to update because you will be aware of the issues, however, if you're working with clients you probably want to make sure nothing unexpected is going to happen.

(function($) {
    $('p').each(function() {
        var search_this = $(this).text();
        if (search_this.indexOf('Highlight phrase') >= 0) {
            $(this).html($(this).html().replace(/Highlight phrase/g, "<span>Highlight </span> phrase"));
        }
    });
})(jQuery);

Obviously this wont highlight any instances of the word "highlight" that have been incorrectly spelled but that, is a different problem.