javascript 检查 div 是否是另一个的后代
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17773852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if div is descendant of another
提问by purplecircles
Best way to find out if element is a descendant of anotherthere is another question, very similiar to this one but its jquery.
找出元素是否是另一个元素的后代的最佳方法还有另一个问题,与这个问题非常相似,但它的 jquery.
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.
那么,我如何在 js 中做到这一点?我有按此顺序嵌套的 div a、b、c、d。另外,不确定是否重要,还有另一个 a、b、c... 和另一个。它不仅仅是一个单一的元素。有许多相同的 id/class。
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.
所以我想看看 d 是否有一个叫做 a.
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.
编辑:另外,我有一个想法,我可以检查“a”的子节点,看看“d”是否是其中之一,但无法实现它。如果有人能让它工作,那就太棒了。
采纳答案by tohava
// x is the element we are checking
while (x = x.parentNode) {
if (x.id == "a") console.log("FOUND");
}
回答by vsr
You can use node.contains
to check if a node contains another node.
https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
您可以node.contains
用来检查一个节点是否包含另一个节点。
https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
回答by Flame Trap
If you want to use pure javascript use node.contains
.
如果您想使用纯 javascript,请使用node.contains
.
e.g.
例如
var a = document.getElementById('a');
var d = document.getElementById('d')
if (a.contains(d)) {
alert('d is a child of a');
}
回答by Infecto
The method closest()
might also be useful in such cases. This method returns the closest ancestor element of an element that matches a given selector (e.g. a class or id). If there is no such element, the method returns null
.
该方法closest()
在这种情况下也可能有用。此方法返回与给定选择器(例如类或 id)匹配的元素的最近祖先元素。如果不存在这样的元素,则该方法返回null
。
let d = document.getElementById("d");
// if there is no ancestor with the id 'a', the method returns null and this evaluates to false:
if(d.closest("#a")){
alert("d is a descendant of an element with the id 'a'");
}
You can find further description and more usage examples on MDN.
您可以在MDN上找到更多描述和更多使用示例。