Categories
JavaScript Answers

Check if a DOM Element is a Child of a Parent with JavaScript?

Spread the love

We can use the contains method to check if a DOM element is a child of a parent.

For instance, if we have the following HTML:

<div id='parent'>
  <div id='child'>
    hello
  </div>
</div>

Then we can do the check by writing:

const contains = (parent, child) => {
  return parent !== child && parent.contains(child);
}

const parentEl = document.querySelector('#parent'),
  childEl = document.querySelector('#child')

if (contains(parentEl, childEl)) {
  console.log('is parent')
}

We have the contains function that gets the parent and child elements.

And we do the check by checking if parent isn’t the same as child and also use the contains method to see if child is inside parent .

We then call contains to see if parentEl is the parent of childEl after getting those elements with document.querySelector .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *