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

3

5

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

Socialize answered 29/10, 2017 at 5:45 Comment(0)
T
5

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.

e.g.

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');
  }
}
Tyrr answered 29/10, 2017 at 5:54 Comment(0)
S
1

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.

Shows answered 29/10, 2017 at 5:56 Comment(0)
G
0

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>
Goins answered 14/11, 2020 at 2:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.