Categories
JavaScript Answers

How to check if an element is a child of a parent with JavaScript?

Spread the love

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

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

How to check if an element is a child of a parent with JavaScript?

To check if an element is a child of a parent with JavaScript, we can use the parent element’s contains method.

For instance, we write

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

to create the contains function that checks if parent isn’t child and that the parent element contains the child element with parent.contains.

Conclusion

To check if an element is a child of a parent with JavaScript, we can use the parent element’s contains method.

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 *