Home > Net >  JavaScript Parent Node contains not working failed to execute 'contains' on 'Node
JavaScript Parent Node contains not working failed to execute 'contains' on 'Node

Time:03-08

I try to change the icon image on click.

I add a class active to make the bottom div appear then i check if the parentNode.contains("active") i should have an image else i should have another image

but this method it doesn't work and i recive this message

Failed to execute 'contains' on 'Node': parameter 1 is not of type 'Node'.

How can i fix this problem?

let drops = document.querySelectorAll('.drop');
let imgs = document.querySelectorAll('.drop .inner-right img');

drops.forEach((drop) => {
    drop.addEventListener("click", function (e) {
        drop.parentNode.classList.toggle("active");
        imgs.forEach((img) => {
            img.src = `../images/new icons/${e.currentTarget.dataset.img}`;
            if(drop.parentNode.contains("active")){
            }else{
                img.src = `../images/${e.currentTarget.dataset.old}`;
            }
        });
    });
});
.box.active .bottom {
    opacity: 1;
    visibility: visible;
}

.box .bottom {
opacity:0;
visibility: hidden;
}
<div >
                            <div  data-img="wasf al khotwa-01.svg" data-old="description.png">
                                <div >
                                    <img src="images/description.png" alt="desc">
                                    <p>Title</p>
                                </div>
                                <i ></i>
                            </div>
                            <div >
                                <p>
Text
                                </p>
                                
                            </div>
                        </div>

CodePudding user response:

you perform contains method on a node and not on the classList of the element

If you want to check if node have a specific class you can use

drop.parentNode.classList.contains("active")

let drops = document.querySelectorAll('.drop');
let imgs = document.querySelectorAll('.drop .inner-right img');

drops.forEach((drop) => {
  drop.addEventListener("click", function(e) {
    drop.parentNode.classList.toggle("active");
    imgs.forEach((img) => {
      img.src = `../images/new icons/${e.currentTarget.dataset.img}`;
      if (drop.parentNode.classList.contains("active")) {
        console.log('win')
      } else {
        img.src = `../images/${e.currentTarget.dataset.old}`;
      }
    });
  });
});
.box.active.bottom {
  opacity: 1;
  visibility: visible;
}

.box.bottom {
  opacity: 0;
  visibility: hidden;
}
<div >
  <div  data-img="wasf al khotwa-01.svg" data-old="description.png">
    <div >
      <img src="images/description.png" alt="desc">
      <p>Title</p>
    </div>
    <i ></i>
  </div>
  <div >
    <p>
      Text
    </p>

  </div>
</div>

  • Related