简体   繁体   中英

How to remove all instances of a class when adding it to a new object in Javascript

Trying to create an active state on the most recently clicked navigation bar button. Currently it will add the class to each item selected but the for...of loop doesn't seem to remove the class.

The nav bar is dynamically made with the following code:

function buildNavBar(){
  for (section of sections){
    numberOfSection = section.getAttribute('data-nav');
    idOfSection = section.getAttribute('id');
    navBarList = document.createElement('li');
    //Uses template literal strings to present the section names in the nav bar
    navBarList.innerHTML = `<a class='menu__link' href='#${idOfSection}'>${numberOfSection}</a>`;

    navBar.appendChild(navBarList);
  }
}
document.getElementById('navbar__list').addEventListener("click", function(event){
  function removeStyle(){
    let funcElem_Style = 'funcElemStyle';
    let menuLinks = document.querySelectorAll('menu__link')
    menuLinks = document.getElementsByClassName('funcElemStyle')
    for(menuLink of menuLinks){
      menuLink.classlist.remove('funcElemStyle')
    }
  }
  event.target.classList.add("funcElemStyle");
});

Don't use for...of to iterate over live HTMLCollections like what getElementsByClassName returns. The reason is that in that loop you are executing code which leads to the element being removed from the live collection instantly, which in turn for the for...of (which internaly works index-based) means that the next element to iterate over actually is the element after the next one, leading to a loop that affects only every 2nd element in the collection.

Instead, spread the result into an array and iterate that.

Next, these two lines don't make sense:

let menuLinks = document.querySelectorAll('menu__link')
menuLinks = document.getElementsByClassName('funcElemStyle')
  1. document.querySelectorAll('menu__link') would find <menu_link> elements (which would be invalid elements and your page probably doesn't have these). You probably meant to select all elements with that CSS class like this: document.querySelectorAll('.menu__link') ?

  2. In the next line you directly overwrite what you just tried to select from the DOM: menuLinks = document.getElementsByClassName('funcElemStyle') .

  3. Inside your anonymous event listener function you declare another function removeStyle() which you never call.

These things said, this is probably what you are after:

document
  .getElementById('navbar__list')
  .addEventListener('click', function(event) {
    for (const menuLink of [...document.querySelectorAll('.menu__link')]) {
      menuLink.classlist.toggle('funcElemStyle', event.target === menuLink)
    }
  }
);

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