skip to Main Content
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


  1. When I try to check if ‘parent’ has a ‘child’ class, I get false, but why?

    Because it doesn’t have that class:

    <div class="parent">
    

    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:

    const childOfParent = document.querySelector(".parent .child");
    
    if (childOfParent) {
      console.log(true);
    } else {
      console.log(false);
    }
    <div class="parent">
      <div class="child"></div>
    </div>

    Or, if you already have the parent object, you can select the child specifically from that element:

    const parent = document.querySelector(".parent");
    const child = parent.querySelector(".child");
    
    if (child) {
      console.log(true);
    } else {
      console.log(false);
    }
    <div class="parent">
      <div class="child"></div>
    </div>
    Login or Signup to reply.
  2. 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 ancestors

    const parent = document.querySelector(".parent");
    const children = Array.from(parent.children);
    
    console.log(
      children.some(child => child.classList.contains("child"))
    );
    <div class="parent">
      <div class="child"></div>
    </div>
    Login or Signup to reply.
  3. Instead of using classList on the .parent (which is incorrect), you can query for a nested .child:

    const parent = document.querySelector('.parent');
    
    if (parent.querySelector('.child') !== null) {
      console.log(true);
    } else {
      console.log(false);
    }
    <div class="parent">
      <div class="child"></div>
    </div>
    Login or Signup to reply.
  4. 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]) {}

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search