I basically need to highlight a particular word in a block of text. For example, pretend 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 to something like this:
<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?
Edit: As Sebastian pointed out, this is quite possible without jQuery - but I was hoping there might be a special method of jQuery which would let you do selectors on the text itself. I'm already using jQuery heavily on this site, so keeping everything wrapped up in jQuery would make things perhaps a bit more tidy.
This question is related to
javascript
jquery
html
$(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
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');
Is it possible to get this above example:
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>"
);
});
};
not to replace text inside html-tags like , this otherwise breakes the page.
I wrote a very simple function that uses jQuery to iterate the elements wrapping 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);
});
});
}
}
More info:
Uses .each()
, .replace()
, .html()
. Tested with jQuery 1.11 and 3.2.
In the above example, reads the 'keyword' to be highlighted and appends span tag with the 'highlight' class. The text 'keyword' is highlighted for all selected classes in the .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;
}
You can use the following function to highlight any word in your 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);
}
Simply target the element that contains the text, choosing the word to colorize and the color of 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's html() function will produce the desired result.
</div>
Usage,
color_word('my_words', 'possible', 'hotpink')
You can use my highlight plugin jQuiteLight, that can also work with regular expressions.
To install using npm type:
npm install jquitelight --save
To install using bower type:
bower install jquitelight
Usage:
// for strings
$(".element").mark("query here");
// for RegExp
$(".element").mark(new RegExp(/query h[a-z]+/));
More advanced usage here
You need to get the content of the p tag and replace all the dolors in it with the highlighted version.
You don't even need to have jQuery for this. :-)
Is it possible to get this above example:
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>"
);
});
};
not to replace text inside html-tags like , this otherwise breakes the page.
Here's a variation that ignores and preserves 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>";});
});
};
I have created a repository on similar concept that changes the colors of the texts whose colors are recognised by html5 (we don't have to use actual #rrggbb values and could just use the names as html5 standardised about 140 of them)
$( document ).ready(function() {_x000D_
_x000D_
function hiliter(word, element) {_x000D_
var rgxp = new RegExp("\\b" + word + "\\b" , 'gi'); // g modifier for global and i for case insensitive _x000D_
var repl = '<span class="myClass">' + word + '</span>';_x000D_
element.innerHTML = element.innerHTML.replace(rgxp, repl);_x000D_
_x000D_
};_x000D_
_x000D_
hiliter('dolor', document.getElementById('dolor'));_x000D_
});
_x000D_
.myClass{_x000D_
_x000D_
background-color:red;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>highlight</title>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>_x000D_
_x000D_
<link href="main.css" type="text/css" rel="stylesheet"/>_x000D_
_x000D_
</head>_x000D_
<body id='dolor'>_x000D_
<p >_x000D_
Lorem ipsum dolor sit amet, consectetuer adipiscing elit._x000D_
</p>_x000D_
<p>_x000D_
Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero._x000D_
Aliquam rhoncus eros at augue. Suspendisse vitae mauris._x000D_
</p>_x000D_
<script type="text/javascript" src="main.js" charset="utf-8"></script>_x000D_
</body>_x000D_
</html>
_x000D_
The reason why it's probably a bad idea to start building your own highlighting function from scratch is because you will certainly run into issues that others have already solved. Challenges:
innerHTML
)Sounds complicated? If you want some features like ignoring some elements from highlighting, diacritics mapping, synonyms mapping, search inside iframes, separated word search, etc. this becomes more and more complicated.
When using an existing, well implemented plugin, you don't have to worry about above named things. The article 10 jQuery text highlighter plugins on Sitepoint compares popular highlighter plugins. This includes plugins of answers from this question.
mark.js is such a plugin that is written in pure JavaScript, but is also available as jQuery plugin. It was developed to offer more opportunities than the other plugins with options to:
Alternatively you can see this fiddle.
Usage example:
// Highlight "keyword" in the specified context
$(".context").mark("keyword");
// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);
It's free and developed open-source on GitHub (project reference).
Source: Stackoverflow.com