Alexander Alexander - 4 months ago 6
HTML Question

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

Answer

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