Mike Mulky
Jenny Sun
<...">

How to use jQuery to highlight text

Suppose I have this HTML code:

<div class="person"> Mike Mulky </div> <div class="person"> Jenny Sun </div> <div class="person"> Jack Kickle </div> 

This jQuery thing will actually filter the corresponding query. For example, when a user enters a text field.

 $('#userInputTextbox').keypress(function(){ $('div.person').hide().filter(':contains("'+THE_QUERY+'")').show(); }); 

It works! And it actually filters out the material. My question is: how do you highlight the words that appear there (query and corresponding text in a DIV)?

+4
source share
2 answers

I would grab a jQuery highlight plugin for this. Using it in the project now to reflect AJAX search results works fine and very easy / simple.

In your case, just add .highlight(THE_QUERY) to the chain.

 $('#userInputTextbox').keypress(function(){ $('div.person').hide().removeHighlight() .filter(':contains("'+THE_QUERY+'")').highlight(THE_QUERY).show(); }); 

The concept is simple, find the text, wrap it in <span class="highlight"></span> , you can style .highlight , but you want to. There .removeHighlight() to match, of course.

+7
source

For a lightweight jQuery highlighting plugin, you can consider http://frightanic.com/web-authoring/lenient-jquery-highlight-plugin/

0
source

Source: https://habr.com/ru/post/1301766/


All Articles