简体   繁体   中英

JS vanilla: how to add a class to a parent element when a child element changes its class?

I would like to change the background to a parent div when a child changes its class:

my structure:

<div class="parent">
  <div class="child-1"></div>
  <div class="child-2"></div>
</div>

My page uses gsap/scroll-trigger that works correctly on scroll with toggleClass:'active' on the triggered child elements

  • When the child-1 has class active i would like to add a class "bg-primary" to the parent;
  • When the child-2 has class active i would like to add a class "bg-green" to the parent;

My attempt in js file:

var parent = document.querySelector('.parent');
var child1 = document.querySelector('.child-1');
var child2 = document.querySelector('.child-2');


if(child1.classList.contains('active')){
     parent.classList.add('bg-primary');
}

if(child2.classList.contains('active')){
     parent.classList.add('bg-green');
}

My code doesn't work, do you have a suggestion to write it correctly? Thank you all.

It might be failing, because JS can't find the elements by class selector. This is because you are missing the ending Semicolon for the div's class. You should change it to this:

<div class="parent">
  <div class="child-1"></div>
  <div class="child-2"></div>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM