使用javascript使用HTML搜索确切的子节点

Search for the exact child node with HTML using javascript

本文关键字:使用 子节点 搜索 javascript HTML      更新时间:2023-09-26

getElementsByTagName("*")将为您获取Depth First Search in Pre-order中的子节点。问题是,如果我在节点的HTML中搜索字符串,就无法判断getElementsByTagName("*")将返回的另一个子节点中是否存在相同的字符串。那么,有没有什么方法可以将节点从叶子迭代到根呢?最有可能的是DFS-Post order可以做到这一点!

例如:

  <div id=""master">
    <div id="id1">
      <div id="id2">
        <span>text</span><i>more text</i>
      </div>
    </div>
  </div>

如果我们正在搜索<i>more text</i>,那么结果的第一个元素的innerHTML以及所有后续元素都将匹配。但我只想要一个完全匹配字符串的孩子。如果我们从树叶开始,那么我们可以在找到文本后break离开。

还有其他想法吗?

如果必须实际执行此文本搜索,请确保nodeType === 3,然后检查nodeValue中的字符串。您实际想要返回的节点是所述节点的parentNode

不过,我认为一般来说这是个坏主意,如果你希望所述元素的内容发生变化(这就是你搜索它的原因),那么就附加一个事件处理程序来侦听变化。

这比您名义上需要的略多,但正是您想要的。

它允许您使用基于属性的许多条件来搜索节点,并给出所有匹配项的数组。

function getNodes(prop, needle, blnMatch, node){
    var results=[], any=(needle==null); 
      node=node||document.documentElement;
      if(node.splice){ node={childNodes:node}; }
    for(var it, i=0, kids=node.childNodes;it=kids[i];i++){
        if(it.childNodes.length){
            results=results.concat(getNodes(prop, needle, blnMatch, it));
        }
        switch(true){
            case    any && it[prop]:
            case    it[prop]===needle:  
            case blnMatch && !!String(it[prop]).match(needle):
             results[results.length]=it; 
        }
    }
   return results;
}//end getNodes()

//for your purpose, you can use it to reach the actual textNode as such:
var node=getNodes("data","more text")[0];
alert([node.data, node.nodeName]) // shows : "more text, #text"

请注意,您可以通过多种方式使用它来特定于任何给定的属性:

getNodes("nodeType", 3);
getNodes("nodeValue", "more text");
getNodes("nodeName", /^(a|link)$/i, true);