简体   繁体   中英

Use JavaScript to find innerHTML text and return parent tag ID

With JavaScript, one often want to use the eg getElementById() function to search for a HTML-tag with a specific ID and return it's innerHTML values.

However, is it possible to achieve the opposite?

<tag1 id="myID1">
    <tag2 id="myID2">
        <tag3>myText</tag3>
    </tag2>
</tag1>

I want to create a function which is looking for the first appearance of "myText" as a innerHTML text and returning it's upper most parent tag id. In this case, if I search for "myText", I expect to return "myID1". How can JavaScript achieve that?

To scan through the children of an html element you could use a recursive function something like:

function findInnerHTMLMatch(s,e){
  if (e.innerHTML===s) return e;
  for (let n=0;n<e.children.length;n++){
    const rtn=findInnerHTMLMatch(s,e.children[n]);
    if (rtn) return rtn;
  }
} 

then if you want to find on the whole page just call findInnerHTMLMatch('myText',document.body) .

This will return the DOM element containing exactly and only the text you specify.

After that I find your requirements unclear. If you are seeking the ultimate parent element then, logically, you will end up with the <html> element every time. So, are you after the top element with an id defined? If not what else and, perhaps most importantly as this will help clarify things, why?


Just because I enjoy thinking about these things... If you want to do it without recursion, a stack works well and is possibly more elegent:

function findInnerHTMLMatch(s,e){
  const stack=[e];
  while (stack.length){
    const el=stack.pop();
    if (el.innerHTML===s) return el;
    stack.push(...el.children);
  }
}

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