Highlight a word with jQuery

I basically need to highlight a specific word in a block of text. For example, pretend that I wanted to highlight the word "dolor" in this text:

<p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. </p> <p> Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris. </p> 

How do I convert the above:

 <p> Lorem ipsum <span class="myClass">dolor</span> sit amet, consectetuer adipiscing elit. </p> <p> Quisque bibendum sem ut lacus. Integer <span class="myClass">dolor</span> ullamcorper libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris. </p> 

Is this possible with jQuery?

Change As Sebastian pointed out, this is quite possible without jQuery - but I was hoping there might be a special jQuery method that allows you to do selectors on the text itself. I already use jQuery heavily on this site, so storing everything that was completed in jQuery would make things perhaps tidier.

+94
javascript jquery html
Sep 23 '08 at 6:45
source share
13 answers

Try highlighting: JavaScript text oriented to jQuery plugin .

 /* highlight v4 Highlights arbitrary terms. <http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html> MIT license. Johann Burkard <http://johannburkard.de> <mailto:jb@eaio.com> */ jQuery.fn.highlight = function(pat) { function innerHighlight(node, pat) { var skip = 0; if (node.nodeType == 3) { var pos = node.data.toUpperCase().indexOf(pat); if (pos >= 0) { var spannode = document.createElement('span'); spannode.className = 'highlight'; var middlebit = node.splitText(pos); var endbit = middlebit.splitText(pat.length); var middleclone = middlebit.cloneNode(true); spannode.appendChild(middleclone); middlebit.parentNode.replaceChild(spannode, middlebit); skip = 1; } } else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) { for (var i = 0; i < node.childNodes.length; ++i) { i += innerHighlight(node.childNodes[i], pat); } } return skip; } return this.length && pat && pat.length ? this.each(function() { innerHighlight(this, pat.toUpperCase()); }) : this; }; jQuery.fn.removeHighlight = function() { return this.find("span.highlight").each(function() { this.parentNode.firstChild.nodeName; with (this.parentNode) { replaceChild(this.firstChild, this); normalize(); } }).end(); }; 

Also try the "updated" version of the original script .

 /* * jQuery Highlight plugin * * Based on highlight v3 by Johann Burkard * http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html * * Code a little bit refactored and cleaned (in my humble opinion). * Most important changes: * - has an option to highlight only entire words (wordsOnly - false by default), * - has an option to be case sensitive (caseSensitive - false by default) * - highlight element tag and class names can be specified in options * * Usage: * // wrap every occurrance of text 'lorem' in content * // with <span class='highlight'> (default options) * $('#content').highlight('lorem'); * * // search for and highlight more terms at once * // so you can save some time on traversing DOM * $('#content').highlight(['lorem', 'ipsum']); * $('#content').highlight('lorem ipsum'); * * // search only for entire word 'lorem' * $('#content').highlight('lorem', { wordsOnly: true }); * * // don't ignore case during search of term 'lorem' * $('#content').highlight('lorem', { caseSensitive: true }); * * // wrap every occurrance of term 'ipsum' in content * // with <em class='important'> * $('#content').highlight('ipsum', { element: 'em', className: 'important' }); * * // remove default highlight * $('#content').unhighlight(); * * // remove custom highlight * $('#content').unhighlight({ element: 'em', className: 'important' }); * * * Copyright (c) 2009 Bartek Szopka * * Licensed under MIT license. * */ jQuery.extend({ highlight: function (node, re, nodeName, className) { if (node.nodeType === 3) { var match = node.data.match(re); if (match) { var highlight = document.createElement(nodeName || 'span'); highlight.className = className || 'highlight'; var wordNode = node.splitText(match.index); wordNode.splitText(match[0].length); var wordClone = wordNode.cloneNode(true); highlight.appendChild(wordClone); wordNode.parentNode.replaceChild(highlight, wordNode); return 1; //skip added node in parent } } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children !/(script|style)/i.test(node.tagName) && // ignore script and style nodes !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted for (var i = 0; i < node.childNodes.length; i++) { i += jQuery.highlight(node.childNodes[i], re, nodeName, className); } } return 0; } }); jQuery.fn.unhighlight = function (options) { var settings = { className: 'highlight', element: 'span' }; jQuery.extend(settings, options); return this.find(settings.element + "." + settings.className).each(function () { var parent = this.parentNode; parent.replaceChild(this.firstChild, this); parent.normalize(); }).end(); }; jQuery.fn.highlight = function (words, options) { var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false }; jQuery.extend(settings, options); if (words.constructor === String) { words = [words]; } words = jQuery.grep(words, function(word, i){ return word != ''; }); words = jQuery.map(words, function(word, i) { return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); }); if (words.length == 0) { return this; }; var flag = settings.caseSensitive ? "" : "i"; var pattern = "(" + words.join("|") + ")"; if (settings.wordsOnly) { pattern = "\\b" + pattern + "\\b"; } var re = new RegExp(pattern, flag); return this.each(function () { jQuery.highlight(this, re, settings.element, settings.className); }); }; 
+80
Sep 23 '08 at 6:58
source share
 function hiliter(word, element) { var rgxp = new RegExp(word, 'g'); var repl = '<span class="myClass">' + word + '</span>'; element.innerHTML = element.innerHTML.replace(rgxp, repl); } hiliter('dolor'); 
+41
Sep 23 '08 at 10:03
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 function 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 breaking DOM events and starting 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 an 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 ).

+29
Sep 24 '15 at 10:08
source share

Here's a variation that ignores and preserves the case:

 jQuery.fn.highlight = function (str, className) { var regex = new RegExp("\\b"+str+"\\b", "gi"); return this.each(function () { this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";}); }); }; 
+11
Apr 20 '10 at 15:49
source share

You can use the following function to highlight any word in the text.

 function color_word(text_id, word, color) { words = $('#' + text_id).text().split(' '); words = words.map(function(item) { return item == word ? "<span style='color: " + color + "'>" + word + '</span>' : item }); new_words = words.join(' '); $('#' + text_id).html(new_words); } 

Just customize the element containing the text by selecting the word to colorize and the color of the choice.

Here is an example :

 <div id='my_words'> This is some text to show that it is possible to color a specific word inside a body of text. The idea is to convert the text into an array using the split function, then iterate over each word until the word of interest is identified. Once found, the word of interest can be colored by replacing that element with a span around the word. Finally, replacing the text with jQuery html() function will produce the desired result. </div> 

Use

 color_word('my_words', 'possible', 'hotpink') 

enter image description here

+3
Mar 01 '18 at 1:26
source share

You can use my highlight jQuiteLight plugin , which can also work with regular expressions.

To set using npm type:

 npm install jquitelight --save 

To set using bower type:

 bower install jquitelight 

Application:

 // for strings $(".element").mark("query here"); // for RegExp $(".element").mark(new RegExp(/query h[az]+/)); 

More advanced use here

+2
Jun 01 '15 at 9:07
source share

Jsfiddle

Uses .each () ,. replace () ,. html (). Tested with jQuery 1.11 and 3.2.

The above example reads the "keyword" that needs to be highlighted and adds a span tag with the "highlight" class. The text "keyword" is highlighted for all selected classes in .each ().

HTML

 <body> <label name="lblKeyword" id="lblKeyword" class="highlight">keyword</label> <p class="filename">keyword</p> <p class="content">keyword</p> <p class="system"><i>keyword</i></p> </body> 

Js

 $(document).ready(function() { var keyWord = $("#lblKeyword").text(); var replaceD = "<span class='highlight'>" + keyWord + "</span>"; $(".system, .filename, .content").each(function() { var text = $(this).text(); text = text.replace(keyWord, replaceD); $(this).html(text); }); }); 

CSS

 .highlight { background-color: yellow; } 
+2
Jun 25 '17 at 8:54 on
source share

You need to get the contents of the tag p and replace all its colored colors with the highlighted version.

You don't even need to have jQuery. :-)

+1
Sep 23 '08 at 6:49
source share

I wrote a very simple function that uses jQuery to iterate over the elements that wrap each keyword with a .highlight class.

 function highlight_words(word, element) { if(word) { var textNodes; word = word.replace(/\W/g, ''); var str = word.split(" "); $(str).each(function() { var term = this; var textNodes = $(element).contents().filter(function() { return this.nodeType === 3 }); textNodes.each(function() { var content = $(this).text(); var regex = new RegExp(term, "gi"); content = content.replace(regex, '<span class="highlight">' + term + '</span>'); $(this).replaceWith(content); }); }); } } 

Additional Information:

http://www.hawkee.com/snippet/9854/

+1
Feb 21 '13 at 16:12
source share

I created a repository on a similar concept that changes the colors of texts whose colors are recognized by html5 (we don’t know, t should use the actual values ​​of #rrggbb and could just use names, since html5 standardized about 140 of them)

colors.js colors.js

 $( document ).ready(function() { function hiliter(word, element) { var rgxp = new RegExp("\\b" + word + "\\b" , 'gi'); // g modifier for global and i for case insensitive var repl = '<span class="myClass">' + word + '</span>'; element.innerHTML = element.innerHTML.replace(rgxp, repl); }; hiliter('dolor', document.getElementById('dolor')); }); 
 .myClass{ background-color:red; } 
 <!DOCTYPE html> <html> <head> <title>highlight</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <link href="main.css" type="text/css" rel="stylesheet"/> </head> <body id='dolor'> <p > Lorem ipsum dolor sit amet, consectetuer adipiscing elit. </p> <p> Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris. </p> <script type="text/javascript" src="main.js" charset="utf-8"></script> </body> </html> 
0
Oct 12 '16 at 20:14
source share

If you really play, you can look at the source of StackOverflow for how it highlights syntax on code blocks;)

Essentially, you just have to dynamically embed HTML (depending on your capabilities).

-2
Sep 23 '08 at 7:05
source share

Is it possible to get this example above:

 jQuery.fn.highlight = function (str, className) { var regex = new RegExp(str, "g"); return this.each(function () { this.innerHTML = this.innerHTML.replace( regex, "<span class=\"" + className + "\">" + str + "</span>" ); }); }; 

Do not replace text inside html tags, for example, it otherwise breaks the page.

-2
Jan 02 '09 at 2:39
source share
 $(function () { $("#txtSearch").keyup(function (event) { var txt = $("#txtSearch").val() if (txt.length > 3) { $("span.hilightable").each(function (i, v) { v.innerHTML = v.innerText.replace(txt, "<hilight>" + txt + "</hilight>"); }); } }); }); 

Jfiddle here

-2
Nov 05 '15 at 13:06
source share



All Articles