Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to check if a DOM element is a child of a parent with JavaScript.

In this article, we’ll look at how to check if a DOM element is a child of a parent with JavaScript.

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

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 .

Conclusion

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

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.