查找具有特定标记的父节点的最佳方式

Best way to find parent node with a specific tag?

本文关键字:父节点 最佳 方式 查找      更新时间:2023-09-26

我多年来在标准JS include中使用的这个函数有现代的等价物吗?

function getParentByTag(elem, lookingFor) {
    var parent = elem.parentNode;
    return parent.tagName === lookingFor ? parent : getParentByTag(parent, lookingFor)
}

我发现它在许多场景中都很有用,例如,查找td的父<table>标签,或输入所在的<form>元素,等等。

我会如下重写它,但概念是一样的:

function getParentByTag(elem, lookingFor) {
  lookingFor = lookingFor.toUpperCase();
  while (elem = elem.parentNode) if (elem.tagName === lookingFor) return elem;
}

您也可以将document.evaluate与诸如ancestor::table之类的xpath一起使用。在非常基本的性能测试中,这大约要贵50%。看起来是这样的:

function getParentByTag(elem, lookingFor) {
  var result = document.evaluate(
    `ancestor::${lookingFor}`, 
    elem, 
    null, 
    XPathResult.FIRST_ORDERED_NODE_TYPE, 
    null);
  return result && result.singleNodeValue;
}