How to Highlight All Occurrences of a Word on a Page with JavaScript or Jquery

How to highlight all occurrences of a word on a page with Javascript or jQuery?

The best way is probably to use a .highlight class to highlight the words and just wrap the matches in a span with that highlight class. Here is a basic example:

var sentences = document.querySelector('#sentences');var keywords = document.querySelector('#keywords');
keywords.addEventListener('click', function(event){ var target = event.target; var text = sentences.textContent; var regex = new RegExp('('+target.textContent+')', 'ig'); text = text.replace(regex, '<span class="highlight">$1</span>'); sentences.innerHTML = text;}, false);
.highlight {    background-color: yellow;}
<div id="keywords">    <span>This</span>     <span>Example</span>.</div><div id="sentences">    This is an example. An example is shown in this. Here is another example.</div>

Using jQuery, how can I highlight all new and existing occurrences of a word as the user types?

You should use /test/g instead of .replace()

Here is a sample which works for your case:

$("#txt").keyup(function() {  var txt = $(this).val();  var keyword = "test";  if (txt.indexOf(keyword) > -1){    $("#page").html(txt.replace(/test/g,'<span class="highlight">' + keyword + '</span>'));  }  else {    $("#page").html(txt);  }});
body {  margin:0;  padding: 0;  font-family: Inter, sans-serif !important;}textarea {  padding: 12x;  font-family: Inter, sans-serif;  font-size: 2em;  height: 1.4em;}.highlight {  color:red !important;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><textarea name="" id="txt" cols="30" rows="10"></textarea><div id="page"></div>

how to highlight all the occurrence of a particular string in a div with java script?

You can get the browser to do the hard work for you using a TextRange in IE and window.find() in other browsers.

This answer shows how to do it. It will match text that crosses element boundaries and does the highlighting for you using document.execCommand().

Alternatively, James Padolsey recently published a script that I haven't used but looks like it could help: http://james.padolsey.com/javascript/replacing-text-in-the-dom-solved/

Highlight specific occurrence of word in text

Just pass in the specific index of the token (character sequence you are looking for) to a function that takes the string, token, and index as parameters. You can now use the 2nd parameter of indexOf to update the beginning of where the string will be searched from using the last result:

const highlighter = (string, token, index) => {  let n = -1  for (let i = 0; i <= index; i++) {    n = string.indexOf(token, n + 1)  }  return string.slice(0, n) + string.slice(n).replace(token, '<span class="highlight">' + token + '</span>')}
const text = 'In a home, there is a room, the room has a door.<br>'const firstRoom = highlighter(text, 'room', 0)const secondRoom = highlighter(text, 'room', 1)
$('#result').append(firstRoom)$('#result').append(secondRoom)
.highlight {  background-color: lightblue;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id="result"></div>

Search and highlight text on page while keeping html structure

Here is a possible base using only native javascript. This behave somewhat like CTRL+F.

This seems to preserve the <td> elements.

The clear function replace the mark elements by a wbr element:

On UTF-8 encoded pages, <wbr> behaves like the U+200B ZERO-WIDTH SPACE
code point.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/wbr

function mark(it){  clearIt()  if (it.length > 2){    let c = new RegExp(it, "ig")     main.innerHTML = main.innerHTML.replace(c,"<mark>"+it+"</mark>")  }  }
function clearIt(){ let b = new RegExp("mark>", "ig") main.innerHTML = main.innerHTML.replace(b,"wbr>")}
mark(search.value)
input[type="text"] {     width: 50%;    margin:10px;    padding: 5px;    float:left;    clear:left;}div{  float:left;  clear:left;  margin:10px 10px;}.bold {  font-weight: 700;}table td {  border: solid 1px #ccc;  padding: 3px;}
<input onfocusout="clearIt()" oninput="mark(this.value)"  value="Lorem" id="search" placeholder="Lorem"><button onclick="mark(search.value)">SEARCH</button><button onclick="clearIt()">CLEAR</button>
<div id="main"><div class="objType" id="item1"> <span class="bold">Accepted</span> Event Relation <table> <tr> <td>Lorem</td> <td>ipsum</td> </tr> </table></div><div class="objType" id="item2"> Case <span class="bold">Status</span> Value <table> <tr> <td>Lorem</td> <td>ipsum</td> </tr> </table></div><div class="objType" id="item3"> External <span class="bold">Data Source</span> <table> <tr> <td>Lorem</td> <td>ipsum</td> </tr> </table></div><div class="objType" id="item4"> Navigation <span class="bold">Link</span> Set <table> <tr> <td>Lorem</td> <td>ipsum</td> </tr> </table></div>
</div>

Highlight a word with jQuery

Try highlight: JavaScript text highlighting jQuery plugin.
Warning: The source code available on this page contains a cryptocurrency mining script, either use the code below or remove the mining script from the script downloaded from the website.

/*

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);
});
};

How can I highlight multiple occurrences of a single word in an HTML element?

Dusted off an old jsFiddle, maybe it gives you ideas:

runExamples();

/** highLighter CODE**/
function highLight(term, hlClass = "highlight", root = document.body) {

if (!term) {
throw TypeError('Highlighter needs a term to highlight anything');
}

term = term instanceof Array ? term.join("|") : term;
hlClass = hlClass || "highlight";
const highlighter = a => `<span class="${hlClass}">${a}</span>`;
const toHtml = node => node.innerHTML =
node.innerHTML.replace(/</g, "<").replace(/>/g, ">");
const children = root.childNodes;

for (let i = 0; i < children.length; i += 1) {
// recurse children if applicable
if (children[i].childNodes.length) {
highLight.call(null, term, hlClass, children[i]);
}

let node = children[i];
let re = RegExp(`(${term})`, "gi");

if (node.nodeType === Node.TEXT_NODE && re.test(node.data)) {
node.data = node.data.replace(re, highlighter);
toHtml(node.parentElement);
}
}
}

function runExamples() {
// highlight the words 'ante', set', 'vul' and 'lacus'
// within the first p of everything within div#example
highLight("ante,sit,vul,lacus".split(","), "highlight2", document.querySelector("#example p:first-child"));

// highlight the word 'magna' everywhere in the document, using class highlight2
highLight("magna", "highlight2");

// highlight the words 'dictum' or 'vestibulum' everywhere in the document
// but only in p elements, using class highlight3
highLight("dictum|vestibulum", "highlight3");

// highlight the word 'example' within h3 element
highLight("example", null, document.querySelector("h3"));

document.addEventListener("click", manual);
}

function manual(evt) {
const origin = evt.target;
if (origin.id.endsWith("Highlight")) {
console.clear();
const removeHighligts = () => document.querySelectorAll("[class^='highlight']")
.forEach(el => el.replaceWith(document.createTextNode(el.textContent)));

if (origin.id.startsWith("manual")) {
const inputValue = document.querySelector("input").value.trim();

if (inputValue) {
removeHighligts();
highLight(inputValue, document.querySelector("#highlighter").value);
}
}

if (origin.id.startsWith("remove")) {
removeHighligts();
}

if (origin.id.startsWith("example")) {
removeHighligts();
runExamples();
}
}

return true;
}
body {
font: 12px/15px normal verdana, arial;
margin: 2rem;
}

.highlight {
font-weight: bold;
background: #ffffc0;
}

.highlight2 {
background: orange;
font-style: italic;
}

.highlight3 {
background: red;
color: white;
}

.inline {
display: inline-block;
}
<h3>a Lorem Ipsum example</h3>
<div id="example">
<div id="lipsum">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas molestie, dolor at posuere egestas,
justo erat molestie ligula, non laoreet justo leo in risus. Aenean ac fermentum mauris. Nam fringilla
accumsan nunc, at egestas ante vulputate at. Aenean et arcu ut elit gravida ornare. Nam nec eros massa,
vel imperdiet lorem. Donec dictum, elit vitae commodo porttitor, urna risus fermentum mauris, sit amet
convallis elit tellus et ligula. <span data-x="demonstrate recursive">Cras nibh lacus</span>, blandit
eu imperdiet nec, aliquet vitae nibh. Aenean eleifend vestibulum tempor. Vivamus vitae erat quis elit
fringilla aliquam.
</p>
<p>
Vestibulum molestie erat quis tortor tincidunt fermentum. Mauris imperdiet cursus auctor. Quisque non
lacinia libero. Sed sed nisi massa, ut vestibulum metus. Nunc ac varius turpis. Pellentesque habitant morbi
tristique senectus et netus et malesuada fames ac turpis egestas. Quisque at tellus ligula.
Aliquam iaculis lacus eget massa tristique accumsan. Integer eu enim sapien, id pretium erat. Ut convallis
dictum lacus, eget mattis magna molestie ut. Proin pretium mattis nisl, a auctor velit aliquam eget.
</p>
<p>
<input type="text" placeholder="enter highlight term" value="sit|lorem|example">
<select id="highlighter">
<option value="highlight" selected>default</option>
<option value="highlight2">orange</option>
<option value="highlight3">red</option>
</select>
</p>
<p>
<button id="manualHighlight">highlight manually</button>
<button id="removeHighlight">remove all highlights</button>
<button id="exampleHighlight">run examples</button>
</p>
</div>
</div>


Related Topics



Leave a reply



Submit