简体   繁体   中英

Javascript addEventListener only add a class to one element

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

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");
    });
});

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