2

I have a <div> which contains some text along these lines:

<div id='log'>alpha bravo charlie delta echo foxtrot</div>

When a user clicks on the text, is there a way to determine which word they clicked upon? I was assuming it would be in the event object, but I am unable to locate any such info there.

$('#log').mouseup(function (ev) {    // tried .click() also
    ev.something ???
});

Note: each word has been added to the <div> individually, so they are their own TextNode in the DOM. Also, for other reasons in this app, it would be preferable not to have to wrap each word in a <span>...</span> if there is any other way. The app uses jQuery, but plain javascript is fine too.

kelsny
  • 23,009
  • 3
  • 19
  • 48
John Hascall
  • 9,176
  • 6
  • 48
  • 72
  • Found an answer to a similar question here : https://stackoverflow.com/a/9304990/14596061 – Afieif Oct 27 '22 at 19:46
  • It's very similar but not exact -- it only works if the user makes a text selection -- it doesn't work for just a click on the text. – John Hascall Oct 27 '22 at 22:05
  • If there is no actual selection the start and end of the range have the same value which helped me discover that the answer to the other question was far more complicated than needed for my problem. Once the selection range is retrieved, all I need is to do `range.setStart(node, 0);` and `range.setEnd(node, node.length - 1);` – John Hascall Oct 27 '22 at 22:36

0 Answers0