简体   繁体   English

使用JavaScript查找innerHTML文本并返回父标记ID

[英]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. 使用JavaScript,人们经常想使用例如getElementById()函数来搜索具有特定ID的HTML标签,并返回其innerHTML值。

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. 我想创建一个函数,将“ myText”的首次外观作为innerHTML文本查找并返回其最上层的父标记id。 In this case, if I search for "myText", I expect to return "myID1". 在这种情况下,如果我搜索“ myText”,则期望返回“ myID1”。 How can JavaScript achieve that? JavaScript如何实现?

To scan through the children of an html element you could use a recursive function something like: 要浏览html元素的子元素,可以使用类似以下内容的递归函数:

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) . 然后,如果要在整个页面上查找,只需调用findInnerHTMLMatch('myText',document.body)

This will return the DOM element containing exactly and only the text you specify. 这将返回仅包含您指定的文本的DOM元素。

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. 如果您正在寻找最终的父元素,那么从逻辑上讲,您每次都会以<html>元素结束。 So, are you after the top element with an id defined? 那么,您是否在定义了id的顶部元素之后? 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);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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