检查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");
}