如果一个元素包含在另一个元素中,如何检查Javascript [英] How to check in Javascript if one element is contained within another
问题描述
如何检查一个DOM元素是否是另一个DOM元素的子元素?有没有内置的方法?例如,如下所示:
How can I check if one DOM element is a child of another DOM element? Are there any built in methods for this? For example, something like:
if (element1.hasDescendant(element2))
或
if (element2.hasParent(element1))
如果没有那么任何想法如何做到这一点?它也需要是跨浏览器。我也应该提到这个孩子可以嵌套在父母以下的许多级别。
If not then any ideas how to do this? It also needs to be cross browser. I should also mention that the child could be nested many levels below the parent.
推荐答案
使用 parentNode
属性应该可以工作。从跨浏览器的角度来看,它也是非常安全的。如果这种关系是一个深层次的关系,你可以简单地检查一下:
Using the parentNode
property should work. It's also pretty safe from a cross-browser standpoint. If the relationship is known to be one level deep, you could check it simply:
if (element2.parentNode == element1) { ... }
如果孩子可以嵌套在父母的任意深处,可以使用一个类似以下函数来测试关系:
If the the child can be nested arbitrarily deep inside the parent, you could use a function similar to the following to test for the relationship:
function isDescendant(parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
这篇关于如果一个元素包含在另一个元素中,如何检查Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!