如何检查一个DOM元素是否是另一个DOM元素的子元素?有什么内置的方法吗?例如,像这样:

if (element1.hasDescendant(element2)) 

or

if (element2.hasParent(element1)) 

如果没有,有什么想法如何做到这一点?它还需要跨浏览器。我还应该提到,子对象可以嵌套在父对象的许多层之下。


当前回答

看一下node# compareDocumentPosition。

function isDescendant(ancestor,descendant){
    return ancestor.compareDocumentPosition(descendant) & 
        Node.DOCUMENT_POSITION_CONTAINS;
}

function isAncestor(descendant,ancestor){
    return descendant.compareDocumentPosition(ancestor) & 
        Node.DOCUMENT_POSITION_CONTAINED_BY;
}

其他关系包括DOCUMENT_POSITION_DISCONNECTED, document_position_precedand document_position_follows。

IE<=8不支持。

其他回答

考虑使用nearest ('.selector')

如果元素和它的任何祖先都不匹配选择器,则返回null。或者返回找到的元素

另一个没有提到的解决方案:

例子

var parent = document.querySelector('.parent');

if (parent.querySelector('.child') !== null) {
    // .. it's a child
}

元素是否为直接子元素并不重要,它在任何深度都可以工作。


或者,使用.contains()方法:

例子

var parent = document.querySelector('.parent'),
    child = document.querySelector('.child');

if (parent.contains(child)) {
    // .. it's a child
}

您可以使用contains方法

Var result = parent.contains(child);

或者你可以尝试使用compareDocumentPosition()

var result = nodeA.compareDocumentPosition(nodeB);

最后一个更强大:它返回一个位掩码作为结果。

TL;DR:图书馆

我建议使用类似dom-helpers的东西,它是由react团队作为常规JS库编写的。

在它们的contains实现中,你会看到一个基于node# contains的实现,并带有一个node# compareDocumentPosition回退。

不支持非常老的浏览器,例如IE <9,我觉得这是可以接受的。

这个答案包含了上面的问题,但是我建议你不要循环。

您应该使用Node。包含,因为它现在是标准的,在所有浏览器中都可用。

https://developer.mozilla.org/en-US/docs/Web/API/Node.contains