简体   繁体   English

JS vanilla:当子元素更改其 class 时,如何将 class 添加到父元素?

[英]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:当孩子更改其 class 时,我想将背景更改为父 div:

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我的页面使用 gsap/scroll-trigger,它在触发的子元素上使用toggleClass:'active'滚动时可以正常工作

  • When the child-1 has class active i would like to add a class "bg-primary" to the parent;当 child-1 激活 class 时,我想向父级添加一个 class “bg-primary”;
  • When the child-2 has class active i would like to add a class "bg-green" to the parent;当 child-2 激活 class 时,我想向父级添加一个 class “bg-green”;

My attempt in js file:我在js文件中的尝试:

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.它可能会失败,因为 JS 无法通过 class 选择器找到元素。 This is because you are missing the ending Semicolon for the div's class. You should change it to this:这是因为您缺少 div 的 class 的结尾分号。您应该将其更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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