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:
JSFiddle
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
keyword
keyword
keyword
JS
$(document).ready(function() {
var keyWord = $("#lblKeyword").text();
var replaceD = "" + keyWord + "";
$(".system, .filename, .content").each(function() {
var text = $(this).text();
text = text.replace(keyWord, replaceD);
$(this).html(text);
});
});
CSS
.highlight {
background-color: yellow;
}