JavaScript检查元素是否为子元素

时间:2016-07-21 12:03:35

标签: javascript html parent-child

如果HTML元素是特定<div>元素的子元素,我如何使用JavaScript进行检查?

if (divElement == child){
   // do something...
}
编辑:谢谢你的回答。我也有关于后代的类似问题,并在Check if div is descendant of another

找到答案

5 个答案:

答案 0 :(得分:2)

以下代码可以帮助您确定父子关系的两个要素。

function isChild (obj,parentObj){
    while (obj != undefined && obj != null && obj.tagName.toUpperCase() != 'BODY'){
        if (obj == parentObj){
            return true;
        }
        obj = obj.parentNode;
    }
    return false;
}

然后使用isChild调用的结果作为条件if语句。

if(isChild(child,divElement)){
    // doSomething...
}

答案 1 :(得分:1)

Client.isSubscribed(topic)

答案 2 :(得分:1)

使用节点的contains函数 - divElement.contains(child)
或如果包含的函数不存在,则使用此函数。

function contains(first, second) {
    var adown = first.nodeType === 9 ? first.documentElement : first;

    if (first === second) {
        return true;
    }

    if (adown.contains) { 
        return adown.contains(second);
    }

    return first.compareDocumentPosition && first.compareDocumentPosition(second) & 16);
}

如果您需要在节点相同时返回false

function notContains(first, second) {
    var adown = first.nodeType === 9 ? first.documentElement : first;

    if (first === second) {
        return false;
    }

    if (adown.contains) { 
        return !adown.contains(second);
    }

    return first.compareDocumentPosition && first.compareDocumentPosition(second) & 16) !== 16;
}

答案 3 :(得分:1)

您可以使用以下任一方法进行检查

parentEl.contains(el)

el.parentNode === parentEl

答案 4 :(得分:-1)

使用nodeName检查

if(elementObj.parentElement.nodeName == "DIV"){
//Your Code
}
相关问题