0

I have DOM document with text content like as:

<p>Content scripts aren't completely cut off from their parent extensions. A content script can exchange messages with its parent extension</p>

When I click over this HTML(text) I get nodeValue as text. But can I get only symbol from text over was click?

For example, I do click over symbol s in text:

<p>They support then</p>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Dev
  • 1,013
  • 7
  • 15
  • 37
  • Unclear what was asked... – epascarello Jan 20 '17 at 18:55
  • 1
    Possible duplicate of [How to determine the position of a character in a div element?](http://stackoverflow.com/questions/8105824/how-to-determine-the-position-of-a-character-in-a-div-element) – Jordan Running Jan 20 '17 at 18:57
  • 1
    @DouglasDaseeco As best I can tell, OP wants to know which character in a text node the user clicked on. The linked answer does exactly that thing. Regardless, I'm looking forward to seeing your faster and more portable solution. – Jordan Running Jan 20 '17 at 20:38
  • Duplicate ... answered here: http://stackoverflow.com/questions/8105824/how-to-determine-the-position-of-a-character-in-a-div-element/41777706#41777706 – Douglas Daseeco Jan 21 '17 at 17:02

1 Answers1

0

So this is a fairly simple pattern when one wants to do operations on single characters, but you have data in blocks of paragraph or word. The first thing to do would be to iterate through all paragraphs, like so:

var paras = document.querySelectorAll('p');
for (var i = 0; i < paras.length; i++) {
    var para = paras[i];

    var text = para.textContent;
    var split = para.split('');
    var newText = '';
    for (var j = 0; j < split.length; j++) {
        newText += '<span class="char">' + split[j] + '</span>';
    }

    para.innerHTML = newText;
}

Then, you would want to set up a click listener on the body or on each paragraph, and the event (having been produced from clicking one of the single-character spans) would contain all the position information of that specific character.

 document.body.addEventListener('click', function(e) {
     if (e.target.classList.contains('char')) {
          console.log(e.clientLeft, e.clientTop);
     }
 });

A possible advantage of this method over Selection.focusNode is that it also allows the single character to be modified as an element, not just ascertained.

Note that this will destroy events and object references -- if you need to persist those, use something like jQuery's replaceWith and iterate over the text nodes.

furkle
  • 5,019
  • 1
  • 15
  • 24