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

3

7

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>.
Suburbicarian answered 20/8, 2015 at 23:37 Comment(3)
When you say "highlight", do you mean just adding a style or select those words? (For the former, you shouldn't bother about node injection, browsers can handle that. For the later, it can be a complicated script which may be more consumptive than the former)Jasminejason
Following is the exact answer you r looking for. https://mcmap.net/q/152113/-highlighting-all-matching-words-in-div-from-text-inputTriform
This is the answer you are looking for. have custom css as well. https://mcmap.net/q/152113/-highlighting-all-matching-words-in-div-from-text-inputTriform
S
11

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/

Spavined answered 20/8, 2015 at 23:54 Comment(10)
Im sorry, how is this not plagiarism of my answer? All you did was convert it to vanilla javascriptBeeswing
Hahaha @AmmarCSE! I started working on this answer when the question was asked (and had no answers), came back and posted it. Believe it or not, I wrote the code from scratch without referencing yours (or anyone else's code). It's funny because you reposted someone else's answer (#32012245) and are trying to call me out on plagiarism. It's not a competition dude, just trying to help people out in my free time.Spavined
Im tired and need to go to bed. Im going to assume you had the best of intentions. Sorry for my bad sportsmanship :)Beeswing
Sorry, did the quick edit because my downvote was locked and they wouldnt let me undo itBeeswing
@Beeswing I hear you on being tired! I definitely agree that there are some surprising overlaps in our code, but really there are only so many ways to accomplish this. Anyway, I'm not worried about up/down votes, it's all good man.Spavined
heh, no I feel ashamed because for a moment I was forgetting what its really about(helping others). Who cares about a couple of votes!Beeswing
This implementation will break any structure in the #sentences divider (if there are paragraphs, anchors, images etc...)Jasminejason
As @Jasminejason pointed out, this is causing issues with other HTML that's in the sentences. I'm now trying to apply this type of solution to each sentence in a list (as opposed to all the <li>'s in a <ul id="sentences">. Any thoughts?Suburbicarian
That was the best I could do with the information you provided, if you want to create a fiddle with a more realistic example I'd be happy to try to help. @T.BrianJonesSpavined
Thanks @RobM. I've created a fiddle that I think will make clear what I'm trying to do. I really appreciate the help. jsfiddle.net/avpLn7bf/2Suburbicarian
E
8

You can wrap words with a specific class only when included in the search result. The wrapping will be removed the next time the word is not part of the search result:

var highlightRe = /<span class="highlight">(.*?)<\/span>/g,
    highlightHtml = '<span class="highlight">$1</span>';

$(function() {
    $('#search').change(function() {
        var term = $(this).val();
        var txt = $('#txt').html().replace(highlightRe,'$1');
        if(term !== '') {
            txt = txt.replace(new RegExp('(' + term + ')', 'gi'), highlightHtml);
        }    
        $('#txt').html(txt);    
    });
});
.highlight {
    background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="text" id="search"/>

<div id="txt">
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.
</div>
Eatton answered 21/8, 2015 at 0:4 Comment(2)
Your code works perfect. but an error.. if i have any tags in the div, it is highlighting that too. ex: <div id= "txt"> <span> hey!! </span> Special </div> and i search for 'sp' it is including span. How to solve this so that it will not include tagsOutrelief
jsfiddle.net/wcu0q4px/1 search for tr in this fiddle. it is giving table content something should be changed here to make it work perfectly. could you help me in finding what is itOutrelief
F
1

The glossarizer plug-in will do this. You put your sentences into a JSON file and each occurrence is given a dotted underline and acts as a tooltip. Set the replaceOnce parameter to false for each occurrence to be highlighted. You can change the js file to customize the appearance, and add any heading tags containing the words, since normally people don't want those highlighted.

Fiveandten answered 20/8, 2015 at 23:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.