找出元素是否是另一个元素的后代的最佳方法还有另外一个问题,这个问题非常类似于它的jquery.
所以,我如何在js中做到这一点?我有div,a,b,c,d按此顺序嵌套.另外,不确定是否重要,还有另一个,b,c ......和另一个.它不仅仅是一个单一元素.有很多相同的id/class.
所以我想看看d是否有一个父级(无论嵌套有多深,只要有一些父级在其上面就可以了),称为a.
编辑:另外,我有这个想法,我可以检查"a"的子节点,看看"d"是否是其中之一,但无法实现它.如果有人可以让它工作,那就太棒了.
vsr*_*vsr 77
您可以node.contains用来检查节点是否包含另一个节点.
https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
Fla*_*rap 22
如果你想使用纯javascript使用node.contains.
例如
var a = document.getElementById('a');
var d = document.getElementById('d')
if (a.contains(d)) {
alert('d is a child of a');
}
Run Code Online (Sandbox Code Playgroud)
小提琴:http://jsfiddle.net/FlameTrap/pwVPC/
toh*_*ava 10
// x is the element we are checking
while (x = x.parentNode) {
if (x.id == "a") console.log("FOUND");
}
Run Code Online (Sandbox Code Playgroud)
该方法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'");
}
Run Code Online (Sandbox Code Playgroud)
您可以在MDN上找到更多描述和更多使用示例。