简体   繁体   中英

find matching words and underline them - but just the words

I have this code where I'm trying to search and underline all instances of a specified word:

 $(".test:contains('moon')").css("text-decoration", "underline");
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="test">The cow jumped over the moon</div>

The above is underlining the whole text.

How can I get it to underline just the instances of "moon"?

Iterate over each element and .replace its innerHTML :

 $(".test:contains('moon')").each(function() { this.innerHTML = this.innerHTML.replace(/moon/g, '<span style="text-decoration: underline">moon</span>'); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="test">The cow jumped over the moon</div>

With your current code, you are applying the style to the whole element that contains the searched word .

You need to loop through all the matched words and replace them accordingly with the desired style in the html of the containing element :

 let word = 'moon'; $(".test:contains('" + word + "')").each(function() { let regex = new RegExp("(" + word + ")", 'g'); $(this).html($(this).text().replace(regex, '<span style="text-decoration: underline">$1</span>')); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <div class="test">The cow jumped over the moon</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM