const parent = document.querySelector(".parent");
if (parent.classList.contains("child")) {
console.log(true);
} else {
console.log(false);
}
<div class="parent">
<div class="child"></div>
</div>
When I try to check if ‘parent’ has a ‘child’ class, I get false, but why?
I used to work with contains() and everything worked out fine, but at one point I got false data. Why, can you help me with this? Point out my mistakes in the code.
4
Answers
Because it doesn’t have that class:
It does contain an element which has that class. If that’s what you’re looking to test, you can select that element and check if the result is
null
. For example:Or, if you already have the
parent
object, you can select the child specifically from that element:The
parent.classList
is an array with classes of the matched element itself, not is children.You can use it’s
.children
property to access it’s direct ancestorsInstead of using
classList
on the.parent
(which is incorrect), you can query for a nested.child
:Your parent container doesn’t have the child class.
The child of the parent has the class.
Either put the class
child
on the parent or use for example sth like this:if(parent.getElementsByClassName('child')[0]) {}