如果一个元素包含在另一个元素中,如何检查 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.
推荐答案
更新: 现在有一种本地方法可以实现这一点.Node.contains()
.在评论和下面的答案中也提到了.
Update: There's now a native way to achieve this. Node.contains()
. Mentioned in comment and below answers as well.
旧答案:
使用 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屋!