Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 718
Alexander Avatar asked Jan 06 '23 16:01

Alexander


2 Answers

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...
}
like image 192
sept08 Avatar answered Jan 08 '23 05:01

sept08


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

like image 40
LuizAsFight Avatar answered Jan 08 '23 07:01

LuizAsFight