检查div是否是另一个的后代 [英] Check if div is descendant of another

查看:130
本文介绍了检查div是否是另一个的后代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

了解最佳方法如果元素是另一个的后代,还有另一个问题,这个问题非常类似于它的jquery。

Best way to find out if element is a descendant of another there is another question, very similiar to this one but its jquery.

所以,我该如何在js中做到这一点?
我有div,a,b,c,d按此顺序嵌套。
也不确定是否重要,还有另一个a,b,c ......和另一个。它不仅仅是一个单一元素。有很多相同的id / class。

so, how do I do it in js ? I have divs a, b, c, d nested in this order. also, not sure if matters, there is another a, b, c... and another. its not just a single element. there is many by same id/class.

所以我想知道d是否有父(无论嵌套有多深,只要有一些父级在它的ok)上叫a。

so I want to see if d has a parent(no matter how deep it is nested, as long as there is some parent on top its ok) called a.

编辑:
也有,我有这个想法,我可以检查a的子节点,看看是否d是其中之一,但无法实现它。如果有人可以使它工作,那就太棒了。

edit: also, I had this idea that I could check childnodes of "a" and see if "d" is one of them, but couldnt implement it. if someone can get it working, itd be awesome.

推荐答案

// x is the element we are checking
while (x = x.parentNode) { 
    if (x.id == "a") console.log("FOUND");
}

这篇关于检查div是否是另一个的后代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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