Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 823
Samy Avatar asked Aug 03 '12 06:08

Samy


2 Answers

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/

like image 123
Tim Down Avatar answered Sep 21 '22 18:09

Tim Down


mark.js seems pretty good for this. Here's my 3 line fiddle to take an html 'string' and highlight the search string.

$(document).ready(function() {
    var html_string = "<b>Major Tom to groundcontrol.</b> Earth is blue <span> and there's something </span> i can do";

    var with_highlight = $("<div/>").html(html_string).mark("can");

    $("#msg").html(with_highlight);
})

Link to jsfiddle

like image 20
Sandeep Muthangi Avatar answered Sep 18 '22 18:09

Sandeep Muthangi