How to remove all classes except the one you clicked?

Jor*_*rdy 0 javascript addclass class removeclass toggleclass

This functions starts when I click on a link. It needs to remove all '.is-active' classes on the elements with the attribute [data-route]. And add the class '.is-active' on the [data-route] element that is connected with the link I clicked on.

    toggle: function(section){
        var sections = document.querySelectorAll('[data-route]');
        for (i = 0; i < sections.length; i++){
            document.querySelector('[data-route]').classList.remove('is-active');
        }
        document.querySelector(section).classList.add('is-active');
    }
Run Code Online (Sandbox Code Playgroud)

But this doesn't work. It doesn't remove the classes?

See example: http://jordypouw.github.io/myFED2/deeltoets1/index.html

P.S. it has to be in vanilla JavaScript.

Sam*_*msy 5

toggle: function(section){
    var sections = document.querySelectorAll('[data-route]');
    for (i = 0; i < sections.length; i++){

        sections[i].classList.remove('is-active');

        // querySelectorAll return an array of dom elements, u can access them directly.

    }

    // I suppose in your case that ' section ' variable is the clicked element so :

    section.classList.add('is-active')

   // if not you have to store the dom element from the event, and add the class here.

}
Run Code Online (Sandbox Code Playgroud)

  • 我们不能在没有循环的情况下做到这一点吗?就像在 Jquery 中一样,我们这样做。 (2认同)