Given an index in a string of HTML, find the closest (parent) DOM element

I have a string, containing only the following HTML:

<p id="p1">Hello there</p>
<p id="p2">Hello there</p>

The "o" of the first "Hello" is at index 15 inside of the string.

Given an index i, such as i = 15, I want to find what HTML DOM the character at this index is in.

In my example it is in paragraph id="p1".

How can I programmatically find out which parent DOM the character at index i is inside a string of markup?

The implementation is this: we have several changes to an article's HTML, with each diff denoted by a start index and an end index. How do we get the paragraph of the article that the change resides in?

At first I thought of using jQuery's :contains, where we can find the DOM of the change given that we know what it is. But if the change is a single space, the search will find multiple results.

1 answer

  • answered 2018-01-11 20:48 selami

    Create a new div element, from index 0 to 16. Find last div inside new created div element.

    var html = $("#content").html();
    var index = 16;
    var d = $("<div></div>");
    d.html(html.substr(0, index));
    var result = d.find("p").last();
    <script src=""></script>
    <div id="content">
      <p id="p1">Hello there</p>
      <p id="p2">Hello there</p>