Alexander
Alexander

Reputation: 971

JavaScript check if element is child

How can I check using JavaScript, if an HTML element is a child of a particular <div> element?

if (divElement == child){
   // do something...
}

EDIT: Thank you for the answers. I also had a similair question about descendants and found the answer here Check if div is descendant of another

Upvotes: 4

Views: 10146

Answers (5)

LuizAsFight
LuizAsFight

Reputation: 242

you can check either starting from parent element, or child element.

1- check if current element is inside the parent element parentEl.contains(el)

or

2- current element's parent is the parentElement we have stored el.parentNode === parentEl

Upvotes: 5

Sagi
Sagi

Reputation: 9284

use contains function of Node - divElement.contains(child)
or this function in case contains does not exists.

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);
}

in case you need to return false when the nodes are the same

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;
}

Upvotes: 1

sept08
sept08

Reputation: 345

The following code may help you determine whether the two elements of parent-child relationships.

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

then use the result of isChild call as condition if statement.

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

Upvotes: 4

Akku
Akku

Reputation: 11

Use nodeName to check

if(elementObj.parentElement.nodeName == "DIV"){
//Your Code
}

Upvotes: -1

henrybbosa
henrybbosa

Reputation: 1125

if (element.parentNode == divElement) { ... }

Upvotes: 3

Related Questions