I think I understand what you are trying to achieve, I have an idea though it's not solid but maybe this can give you a head start.
Get the highlighted text and find all similar text in the body and wrap it with <span>
. Then get the <span>
index to determine the highlighted text's occurrence.
We can get that occurrence value by getting the mouse click
event coordinates. Then find the <span>
located on that coordinates and retrieve its index.
We get the highlighted text with:
var text;
if(window.getSelection){
text = window.getSelection().toString();
}else if (document.selection && document.selection.type != 'Control'){
//for IE prior to 9
text = document.selection.createRange().text;
}
Then check if the text is not empty or not spaces and wrap all similar text with span:
if($.trim(text).length){
//wrap each word similar to the highlighted text with <span>
var regex = new RegExp(text,'g')
$('body').html($('body').html().replace(regex, '<span>'+text+'</span>'));
}
Now it's all wrapped, we need to get the original click coordinates:
$('body').on('click',function(e){
//get the x and y coords
var offset = $(this).offset(),
x = e.clientX - offset.left,
y = e.clientY - offset.top,
})
Get the new span located on that coordinates with:
var el = document.elementFromPoint(x, y)
Here is the jsfiddle