Search code examples
javascriptjquerycsshighlighting

How to highlight all occurrences of a word on a page with Javascript or jQuery?


I have a list of keywords and then a list of sentences containing those keywords on a page. I'd like to make the keyword list clickable. When a user clicks on a keyword, all occurrences of that keyword would highlight in the sentences.

How can I do this with jQuery or raw Javascript?

The only way I can think is to wrap every word on the page with a class containing itself as the class name. Then make the keywords buttons that add a highlight class to the matching word classes. This may work, but seems like a LOT of unnecessary code injection.

List of Keywords

<button>this</button>
<button>example</button>

Sentences

<span class='word_this'>This</span> <span class='word_is'>is</span> <span class='word_an'>an</span> <span class='word_example'>example</span>.

Solution

  • The best way is probably to use a .highlight class to highlight the words and just wrap the matches in a span with that highlight class. Here is a basic example:

    var sentences = document.querySelector('#sentences');
    var keywords = document.querySelector('#keywords');
    
    keywords.addEventListener('click', function(event){
        var target = event.target;
        var text = sentences.textContent;
        var regex = new RegExp('('+target.textContent+')', 'ig');
        text = text.replace(regex, '<span class="highlight">$1</span>');
        sentences.innerHTML = text;
    }, false);
    .highlight {
        background-color: yellow;
    }
    <div id="keywords">
        <span>This</span> 
        <span>Example</span>.
    </div>
    <div id="sentences">
        This is an example. An example is shown in this. Here is another example.
    </div>

    Fiddle: https://jsfiddle.net/xukay3hf/3/

    Updated Fiddle which leaves existing word highlighting: https://jsfiddle.net/avpLn7bf/3/