javascript - How do I find how many occurences are there of a highlighted string, and which occurence is it? -


as title says, have website text inside div, there way highlight part of , know occurence is? if text has 4 occurences of word "something", , highlight 3rd, how information using javascript/jquery?

http://jsfiddle.net/g09g35xa/6/

here's method seems work. highlight string want , when click button alert index of highlighted word in div.

markup:

<div id="thediv"> <p>the quick brown quick fox jumps on lazy dog</p> </div> <br /> <input id="findindex" type="button" value="find index of highlighted string" /> 

and js:

function getselectedhtml() {     try {         if (window.activexobject) {             var c = document.selection.createrange();             return c.htmltext;         }          return getselection().getrangeat(0).tostring();     } catch (e) {         if (window.activexobject) {             return document.selection.createrange();         } else {             return getselection();         }     } }  function surroundselectedelement() {     var nnd = document.createelement("span");     nnd.setattribute("id","actualselectedelement");     var w = getselection().getrangeat(0);     w.surroundcontents(nnd); }  $(function() {     // save originalhtml reset later     var originalhtml = $("#thediv").html();     $("#findindex").click( function() {                 // selected string         var selectedtext = getselectedhtml();         if(selectedtext === '')             return;          // surround selected area span, id = actualselectedelement         surroundselectedelement();          // build regex find occurrences of string selected         var re = new regexp(selectedtext, "g");          // replace instances of string span tags, class = selectedtext         $("#thediv").html($("#thediv").html().replace(re, "<span class='selectedtext'>" + selectedtext + "</span>"));          // actual 1 selected contained within span id=actualselectedelement, spans class=selectedtext , find index of 1 span actualselectedelement         var index = $('span.selectedtext').index($('span#actualselectedelement span.selectedtext'));          alert(index);          // reset html original         $("#thediv").html(originalhtml);     }); }); 

Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -