简体   繁体   中英

Get all parent HTML tags from a position within a HTML string

Is there a simple way to get all the 'parent HTML tags' from a position within a HTML string?

For example:

'<div><div>foo</div><p>foo2</p>foo3*caret position here*' : returns '<div>' (the first div)
'<div><div>foo</div><p>foo2*caret position here* : returns '<div><p>' 
'<div><div><div>foo*caret position here* : returns '<div><div><div>'

You need to convert the string into DOM and navigate the tree.

 function getAllParents(htmlStr) { //find cursor text and replace it with an element we can find htmlStr = htmlStr.replace('*cursor*', '<span class="cursor"></span>'); //make a div we can inject our html into var div = document.createElement("div"); //turn our string into dom we can navigate div.innerHTML = htmlStr; //find the cursor var cur = div.getElementsByClassName("cursor")[0], elems = []; //loop over all parents while (cur) { elems.unshift(cur); cur = cur.parentNode; } elems.shift() //remove our div that holds the html elems.pop() //remove the cursor element we injected return elems; //return the parents } console.log(getAllParents("<div><div><span><em>aaa*cursor*aaa</em></span></div></div>")); console.log(getAllParents("<div><div>*cursor*<span><em>aaaaaa</em></span></div></div>")); console.log(getAllParents("*cursor*<div><div><span><em>aaaaaa</em></span></div></div>"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM