如何递归搜索所有parentNodes [英] How to recursively search all parentNodes

查看:76
本文介绍了如何递归搜索所有parentNodes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,如何递归地找出元素的所有父节点。
假设我有以下代码片段

I want to know, how to find out recursively all parent nodes of an element. Suppose i have following snippet

< a href =#>< font> Hello< / font>< ; / a>

在此我想知道字体标签的父节点是否是锚点标记。
现在这可以通过简单地检查.parentNode属性来实现。但是,如果有以下情况,如

In this I would like to find out whether font tag's parent node is an anchor tag or not. Now this can be achieved by simply checking .parentNode property. But what if there are following cases like,

< a href =#>< font>< b> Hello< b>< / font>< / a>

< a href =#>< font>< b>< u> Hello< / u>< b>< / font>< / a>

所以,基本上,如何知道我们是否已经达到顶级的父节点?

So, basically, how to know if we have reached the top most parent node ?

推荐答案

您可以从元素遍历到根目录,寻找所需的标签:

You can traverse from an element up to the root looking for the desired tag:

function findUpTag(el, tag) {
    while (el.parentNode) {
        el = el.parentNode;
        if (el.tagName === tag)
            return el;
    }
    return null;
}

您可以使用起始元素调用此方法:

You call this method with your start element:

var el = document.getElementById("...");  // start element
var a = findUpTag(el, "A");   // search <a ...>
if (a) console.log(a.id);

这篇关于如何递归搜索所有parentNodes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆