I'm trying to get the html tag object that wraps the char in specific position. for example:
position = 34
(first 'e' in the word "everyone")
<html><body><h1>Welcome</h1><p>Hi everyone</p><body></html>
Is there a way to get the 'p' tag that wraps this position?
I need the tag object itself, for changing its innerHTML.
CodePudding user response:
One way is to put an element in the string at that position, then add that string to another element and use querySelector and parentNode to get the p tag.
I used BR with an ID, because when using a div etc, it wasn't giving me what I wanted.
let html = '<html><body><h1>Welcome</h1><p>Hi everyone</p></body></html>';
let position = 34;
let obj = "<br id='posObject' />";
html = [html.slice(0, position), obj, html.slice(position)].join('');
let el = document.createElement("div");
el.innerHTML = html;
console.log(el.querySelector("#posObject").parentNode)