Skip to content Skip to sidebar Skip to footer

Getting Text At Clicked Location In An HTML Element

I have a div element containing some text. When the user clicks a word inside that div I'd like to highlight just that word. In order to do this I need to know what character po

Solution 1:

If your page is auto-generated, you might consider pre-processing the page by putting a <span class = 'word'> around every word in every selectable div. You might be able to this with javascript after the fact, and I think that would be your solution regardless, but pre-processing would make it easier.

The problem with relying on the absolute position of the word is that users can scale their fonts, which makes this task especially hard. By wrapping a span around every individual word, you can easily select which word was clicked by applying the click event to the span elements.


Post a Comment for "Getting Text At Clicked Location In An HTML Element"