How can I add and remove an active class to an element in pure JavaScript

前端 未结 9 1171
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 20:29

I am trying to make a navigation menu I did all the HTML and CSS when come to javascript I am struck in the middle I am able to add a class to the

9条回答
  •  暖寄归人
    2020-12-17 20:49

    You could use classList methods to add, remove, or toggle.

    First remove class name from previous one:

    // assuming there's only one with such class name
    // otherwise you need querySelectorAll and a loop
    document.querySelector('.active').classList.remove('active')
    

    Then add it to the new element:

    e.target.classList.add('active')
    

提交回复
热议问题