Samy Samy - 1 month ago 6
HTML Question

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

i need to highlight all the occurrences of a string in particular div by selecting a string,
once i select a word and click a button it need to highlight all its occurrence inside a div,

eg - if i select


cricket is game


it should highlight all the occurrences of cricket is game some may be like this cricket is game or cricket is game

enter image description here

Answer

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/