Search code examples
javascripttextselection

Determine textNode at character number of paragraph ancestor


Let's say we have the following HTML:

<p>1234<strong>5678</strong>.</p>

Let's say that if we wanted to consider '234' a selection it's relative index to the p parent element would be 1-3 (using 0 as starting index).

How do I determine what node (e.g. the textNode) is at character index 7 of the paragraph?

The obvious answer is the textNode belonging to the strong element: how do I do that presuming the text is no selection (e.g. there is no window.getSelection()) to reference?


Solution

  • This turned out to actually be a bit easier than I thought however it may have limitations (that others are welcomed to expand upon).

    var tl = 0;//text length, increment per node's textContent.length
    for (var i = 0; i < element.childNodes.length; i++)
    {
     console.log(i+' = '+ac.childNodes[i].textContent.length);
     tl = (tl + element.childNodes[i].textContent.length);
    }
    

    So we can use break when the length is suddenly equal to or greater than whatever character index reference we're looking for.

    There may be a complexity of multiple nested nodes such as a em element nested within a strong element to be considered which others are welcome to expand upon.