Reputation: 192
As the title says, say I have some website with a text inside some div, is there a way to highlight some part of it and know which occurence it is? If a text has 4 occurences of the word "something", and I highlight the 3rd, how do I get that information using Javascript/JQuery?
Upvotes: 1
Views: 47
Reputation: 2557
http://jsfiddle.net/g09g35xa/6/
Here's a method that seems to work. Highlight the string you want and when you click the button it will alert the index of that highlighted word in the div.
Markup:
<div id="theDiv">
<p>The quick brown quick fox jumps over the lazy dog</p>
</div>
<br />
<input id="findIndex" type="button" value="Find Index Of Highlighted String" />
And the 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 to reset later
var originalHtml = $("#theDiv").html();
$("#findIndex").click( function() {
// get the selected string
var selectedText = getSelectedHTML();
if(selectedText === '')
return;
// surround the selected area with a span, id = actualSelectedElement
surroundSelectedElement();
// build Regex to find all occurrences of string that was selected
var re = new RegExp(selectedText, "g");
// replace instances of string with span tags, class = selectedText
$("#theDiv").html($("#theDiv").html().replace(re, "<span class='selectedText'>" + selectedText + "</span>"));
// the actual one selected is contained within a span with id=actualSelectedElement, so get all spans with class=selectedText and find the index of the one with the extra span actualSelectedElement
var index = $('span.selectedText').index($('span#actualSelectedElement span.selectedText'));
alert(index);
// reset the html back to original
$("#theDiv").html(originalHtml);
});
});
Upvotes: 1
Reputation: 55972
you could:
Upvotes: 1