JQuery search in a static HTML page with highlighting of the found word

I am trying to do a simple search inside a static HTML page using jQuery. I should mention that this is only my first experience with jQuery.

I am trying to change the background of a found word on a page, and this is what I have tried so far:

myJavascript.js:

$(document).ready(function(){ $('#searchfor').keyup(function(){ page = $('#all_text').text(); searchedText = $('#searchfor').val(); $("p:contains('"+searchedText+"')").css("color", "white"); }); }); 

Here is also the HTML code:

page.html:

 <html> <head> <title>Test page</title> </head> <body bgcolor="#55c066"> <input type="text" id="searchfor"></input> <p id="all_text">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum. <font color="red">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tinci futurum.</font> </p> </body> <script src="jquery-1.7.2.min.js"></script> <script src="myJavascript.js"></script> </html> 

After checking the page with Firebug, I see that the variables in jQuery really get the value from the input field, but I assume that I messed up the highlighted part.

Thanks in advance for your help!

+14
jquery html css search highlight
source share
6 answers

Do something like this

  $("p:contains('"+searchedText+"')").each( function( i, element ) { var content = $(element).text(); content = content.replace( searchedText, '<span class="search-found">' + searchedText + '</span>' ); element.html( content ); }); .search-found { text-decoration: underline; } 

ps this will work only if each of the "elements" has only text content, otherwise it will remove the child nodes.

EDIT: removed extra ")" in each callback

+9
source share

Why using the backlight self-protection feature is a bad idea

The reason itโ€™s probably a bad idea to start creating your own highlighting feature from scratch is because you are likely to run into problems that others have already solved. Tasks:

  • You will need to remove text nodes with HTML elements in order to highlight your matches without destroying DOM events and triggering DOM regeneration again and again (which would be, for example, using innerHTML )
  • If you want to remove the selected elements, you will need to delete the HTML elements with their contents, as well as combine the separated text nodes for further search. This is necessary because each highlighter plugin searches inside text nodes for matches, and if your keywords are divided into several text nodes, they will not be found.
  • You will also need to create tests to make sure your plugin works in situations you have not thought about. And I'm talking about cross-browser tests.

Sounds complicated? If you need some features, such as ignoring some highlight elements, diacritical mapping, matching synonyms, searching inside the iframe, split search by words, etc., this becomes more and more complicated.

Use existing plugin

When using an existing, well-implemented plugin, you donโ€™t have to worry about the above things. Article 10 of jQuery illuminated text plugins on Sitepoint compares popular highlight plugins. This includes plugins for answering this question.

Take a look at mark.js

mark.js is a plugin that is written in pure JavaScript, but is also available as a jQuery plugin. It was designed to offer more features than other settings plugins:

  • search for keywords separately, not the full term
  • map diacritics (For example, if "justo" should also match "justรฒ")
  • ignore matches inside custom elements
  • use custom highlight element
  • use custom highlight class
  • display of user synonyms
  • search inside inside iframe
  • get conditions not found

Demo

Alternatively, you can see this script .

Usage example :

 // Highlight "keyword" in the specified context $(".context").mark("keyword"); // Highlight the custom regular expression in the specified context $(".context").markRegExp(/Lorem/gmi); 

This is a free and developed open-source on GitHub ( link to the project ).

Mark.js keyword selection example with code

 $(function() { $("input").on("input.highlight", function() { // Determine specified search term var searchTerm = $(this).val(); // Highlight search term inside a specific context $("#context").unmark().mark(searchTerm); }).trigger("input.highlight").focus(); }); 
 mark { background: orange; color: black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/mark.js/7.0.0/jquery.mark.min.js"></script> <input type="text" value="test"> <div id="context"> Lorem ipsum dolor test sit amet </div> 
+18
source share

Here is mine: http://jsfiddle.net/x8rpY/1/

JS:

 $('#searchfor').keyup(function(){ var page = $('#all_text'); var pageText = page.text().replace("<span>","").replace("</span>"); var searchedText = $('#searchfor').val(); var theRegEx = new RegExp("("+searchedText+")", "igm"); var newHtml = pageText.replace(theRegEx ,"<span>$1</span>"); page.html(newHtml); }); 

CSS

 #all_text span { text-decoration:underline; background-color:yellow; } 

Also works for repeated searches.

+8
source share

 $(function() { $("input").on("input.highlight", function() { // Determine specified search term var searchTerm = $(this).val(); // Highlight search term inside a specific context $("#context").unmark().mark(searchTerm); }).trigger("input.highlight").focus(); }); 
 mark { background: orange; color: black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/mark.js/7.0.0/jquery.mark.min.js"></script> <input type="text" value="test"> <div id="context"> Lorem ipsum dolor test sit amet </div> 
+3
source share

(why do you want to use background color, not color, for background)

I would create a css class for the regular and separate (inherited) css class for the selected text, and then use jQuery to change the css class when you find what you are looking for.

Only my initial thoughts, though not sure if there is a better way to do this.

EDIT: if you want to change only a specific word, you will have to change innerHTML to put it in a separate tag at this point.

-one
source share

Here is another example that I quickly hacked: http://jsfiddle.net/VCJUX/

-one
source share

All Articles