How to highlight all the appearance of a specific row in a div using java script?

I need to select all occurrences of a line in a particular div, selecting a line, as soon as I select a word and click the button, it needs to select all its occurrences inside the div,

for example - if I choose

cricket - game

he must highlight all occurrences of cricket - this is a game that can be like this cricket - game or cricket - game

enter image description here

+4
source share
7 answers

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

This answer shows how to do this. It will correspond to the text that crosses the borders of the elements and makes a selection for you using document.execCommand() .

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

+4
source

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

 $(document).ready(function() { var html_string = "<b>Major Tom to groundcontrol.</b> Earth is blue <span> and there something </span> i can do"; var with_highlight = $("<div/>").html(html_string).mark("can"); $("#msg").html(with_highlight); }) 

Jsfiddle link

+3
source

This should start: http://jsfiddle.net/wDN5M/

 function getSelText() { var txt = ''; if (window.getSelection) { txt = window.getSelection(); } else if (document.getSelection) { txt = document.getSelection(); } else if (document.selection) { txt = document.selection.createRange().text; } document.getElementById('mydiv').innerHTML = document.getElementById('mydiv').innerHTML.split(txt).join('<span class="highlight">' + txt + '</span>'); } 

See: Get selected text on a page (not in a text box) using jQuery

If you want it to work across element boundaries, your code should be more active than this. jQuery makes your life easier when doing DOM traversal and manipulation.

+2
source

You can try this script

Demo

in highlightSearchTerms function of this script is var bodyText = document.body.innerHTML; gets replaced by your division and how it will complete the task for you.
 /* * This is the function that actually highlights a text string by * adding HTML tags before and after all occurrences of the search * term. You can pass your own tags if you'd like, or if the * highlightStartTag or highlightEndTag parameters are omitted or * are empty strings then the default <font> tags will be used. */ function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) { // the highlightStartTag and highlightEndTag parameters are optional if ((!highlightStartTag) || (!highlightEndTag)) { highlightStartTag = "<font style='color:blue; background-color:yellow;'>"; highlightEndTag = "</font>"; } // find all occurences of the search term in the given text, // and add some "highlight" tags to them (we're not using a // regular expression search, because we want to filter out // matches that occur within HTML tags and script blocks, so // we have to do a little extra validation) var newText = ""; var i = -1; var lcSearchTerm = searchTerm.toLowerCase(); var lcBodyText = bodyText.toLowerCase(); while (bodyText.length > 0) { i = lcBodyText.indexOf(lcSearchTerm, i+1); if (i < 0) { newText += bodyText; bodyText = ""; } else { // skip anything inside an HTML tag if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) { // skip anything inside a <script> block if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) { newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag; bodyText = bodyText.substr(i + searchTerm.length); lcBodyText = bodyText.toLowerCase(); i = -1; } } } } return newText; } /* * This is sort of a wrapper function to the doHighlight function. * It takes the searchText that you pass, optionally splits it into * separate words, and transforms the text on the current web page. * Only the "searchText" parameter is required; all other parameters * are optional and can be omitted. */ function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag) { // if the treatAsPhrase parameter is true, then we should search for // the entire phrase that was entered; otherwise, we will split the // search string so that each word is searched for and highlighted // individually if (treatAsPhrase) { searchArray = [searchText]; } else { searchArray = searchText.split(" "); } if (!document.body || typeof(document.body.innerHTML) == "undefined") { if (warnOnFailure) { alert("Sorry, for some reason the text of this page is unavailable. Searching will not work."); } return false; } var bodyText = document.body.innerHTML; for (var i = 0; i < searchArray.length; i++) { bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag); } document.body.innerHTML = bodyText; return true; } /* * This displays a dialog box that allows a user to enter their own * search terms to highlight on the page, and then passes the search * text or phrase to the highlightSearchTerms function. All parameters * are optional. */ function searchPrompt(defaultText, treatAsPhrase, textColor, bgColor) { // This function prompts the user for any words that should // be highlighted on this web page if (!defaultText) { defaultText = ""; } // we can optionally use our own highlight tag values if ((!textColor) || (!bgColor)) { highlightStartTag = ""; highlightEndTag = ""; } else { highlightStartTag = "<font style='color:" + textColor + "; background-color:" + bgColor + ";'>"; highlightEndTag = "</font>"; } if (treatAsPhrase) { promptText = "Please enter the phrase you'd like to search for:"; } else { promptText = "Please enter the words you'd like to search for, separated by spaces:"; } searchText = prompt(promptText, defaultText); if (!searchText) { alert("No search terms were entered. Exiting function."); return false; } return highlightSearchTerms(searchText, treatAsPhrase, true, highlightStartTag, highlightEndTag); } 
+1
source

I would use jQuery to iterate over all the elements in your div (I don't know if you have other elements in the div) and then a regular expression and make a greedy match to find all occurrences of the selected line in your text (s) in the elements.

0
source

First you need to find the necessary substrings in the desired text and wrap them with <span class = "search-highlight">. Each time you need to highlight other lines, you simply get all .search-highlight spans and turn their outerHtml into innerHtml. Therefore, the code will be close to:

 function highLight(substring, block) { $(block).find(".search-highlight").each(function () { $(this).outerHtml($(this).html()); }); // now the block is free from previous highlights $(block).html($(block).html().replace(/substring/g, '<span class="search-highlight">' + substring + '</span>')); } 
0
source
 <form id=f1 name="f1" action="" onSubmit="if(this.t1.value!=null && this.t1.value!='') findString(this.t1.value);return false" > <input type="text" id=t1 name=t1size=20> <input type="submit" name=b1 value="Find"> </form> <script> var TRange=null; function findString (str) { if (parseInt(navigator.appVersion)<4) return; var strFound; if (window.find) { // CODE FOR BROWSERS THAT SUPPORT window.find strFound=self.find(str); if (!strFound) { strFound=self.find(str,0,1); while (self.find(str,0,1)) continue; } } else if (navigator.appName.indexOf("Microsoft")!=-1) { // EXPLORER-SPECIFIC CODE if (TRange!=null) { TRange.collapse(false); strFound=TRange.findText(str); if (strFound) TRange.select(); } if (TRange==null || strFound==0) { TRange=self.document.body.createTextRange(); strFound=TRange.findText(str); if (strFound) TRange.select(); } } else if (navigator.appName=="Opera") { alert ("Opera browsers not supported, sorry...") return; } if (!strFound) alert ("String '"+str+"' not found!") return; } </script> 
0
source

All Articles