Change selected text color bg
HTML
<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" />
JavaScript
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;
// surrong the selected area with a div
surroundSelectedElement();
// build Regex to find all occurances of string that was selected
var re = new RegExp(selectedText, "g");
// replace intances of string with span tags
$("#theDiv").html($("#theDiv").html().replace(re, "<span class='selectedText'>" + selectedText + "</span>"));
// the actual one selected is contained within a span actualSelectedElement, so get all selectedText spans 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);
});
});