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.