I am building a JS script and I want to get the position of a word in a text by clicking on it. For example:
This is my paragraph and I want to get the word paragraph of this text.
Let's assume that I am clicking on the paragraph that appears for second time in this text. The result should be 12 as it's the 12th word. How could I do that?
So far I can double click on a word and get it but I also need its position.
<script> $(document).ready(function() {
var p = $('p');
p.css({ cursor: 'pointer' });
p.dblclick(function(e) {
var range = window.getSelection() || document.getSelection() || document.selection.createRange();
var word = $.trim(range.toString());
if(word != '') {
alert(word);
}
range.collapse();
e.stopPropagation();
});
});</script>
<p>This is my paragraph and I want to get the word paragraph of this text.</p>
`, you get the tag element in the whole, not its content, so is not possible.
– RompePC Jun 20 '17 at 12:52