简体   繁体   中英

Vanilla JS - Can add/remove class on child elements but all are active

I am able to add and remove the classes on the child elements but all are active. I am trying to add & remove only on one active element at a time. What am I missing?

<ul id="parent" class="container">
  <li class="child"><a href="#one">one</a></li>
  <li class="child"><a href="#two">two</a></li>
  <li class="child"><a href="#three">three</a></li>
</ul>


document.addEventListener("DOMContentLoaded", function() {

  const parent = document.querySelector('#parent');
  parent.style.backgroundColor = 'blue';
  const childrens = document.querySelectorAll('.child');
  const child = document.querySelector('.child a')

  Array.prototype.forEach.call(
   document.querySelectorAll('.child'),
    function(element) {
      element.onclick = addActive;
    }
  );

 function addActive(element){
  element = this;
   if(element.classList.contains('active')) {
    element.classList.remove('active');
   } else {
    element.classList.add('active');
   }
 }
});

Here's a: codepen

Right now you're adding/removing the active class only from the clicked element. You'll have to remove the class from all elements before you set the clicked one as active.

eg

function addActive(element) {
  element = this;
  if (element.classList.contains('active')) {
    element.classList.remove('active');
  } else {
    childrens.forEach(function(e) {
      e.classList.remove('active');
    });
    element.classList.add('active');
  }
}

One solution is to remove the active class from all elements first:

function addActive(element) {

  childrens.forEach(function(elem) {
    elem.classList.remove("active");
  });

  element = this;
  if (element.classList.contains("active")) {
    element.classList.remove("active");
  } else {
    element.classList.add("active");
  }
}

Here is a working Codepen example .

Here maybe the most straight forward way to toggle through your child elements using pure js.

<ul id="parent" class="container">
 <li class="child"><a href="#one">one</a></li>
 <li class="child"><a href="#two">two</a></li>
 <li class="child"><a href="#three">three</a></li>
</ul>

<script>
//get children 
var theChildren = document.querySelector('#parent').children;

//set event listener for to each child
function selectChild(child) {
child.addEventListener('click', function() {
    var checkChildStatus = document.querySelector('#parent .selected');
    if (checkChildStatus) {
        checkChildStatus.classList.remove('selected');
    }
    
    child.classList.add('selected');        
 });
}

//loop through all children
[...theChildren].forEach(selectChild);
</script>

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