Home > Enterprise >  Javascript addEventListener only add a class to one element
Javascript addEventListener only add a class to one element

Time:08-09

I am trying to create a tab-like system where when you click a tab, it removes the classes from other tabs and adds them to the clicked class

heres the code

JS:

const tabs = document.getElementsByClassName('Tab');

for (let tab=0; tab < tabs.length; tab  ){
  tabs[tab].addEventListener('click', (e)=>{
    for (let tab=0; tab < tabs.length; tab  ){
      e.target.classList.remove('active-tab')
    }
    e.target.classList.add('active-tab')
  })
}

css:

.active-tab {
  border-bottom: 10px solid pink;
}

It is actually adding the class and adding a pink underline, but it doesn't remove the other classes, so all the tabs can have the underline

Example:

The Error

CodePudding user response:

It looks like the reason it is not removing any of the classes is because you are using e.target.classList.remove('active-tab') which removes the class from the element/tab that was clicked. You are looping through the elements/tabs, but not actually selecting any of them.

So you would want to use something like tabs[tab].classList.remove('active-tab') instead.

const tabs = document.getElementsByClassName('Tab');

for (let tab=0; tab < tabs.length; tab  ){
  tabs[tab].addEventListener('click', (e)=>{
    for (let tab=0; tab < tabs.length; tab  ){
      tabs[tab].classList.remove('active-tab')
    }
    e.target.classList.add('active-tab')
  })
}

For the sake of avoiding for loops with list of elements/arrays, here is alternative way to do this same thing

document.querySelectorAll('.Tab').forEach(el => {
    el.addEventListener("click", e => {
        document.querySelectorAll("active-tab").forEach(t => {
            t.classList.remove("active-tab");
        });
        e.target.classList.add("active-tab");
    });
});
  • Related