add class with JavaScript

前端 未结 7 2048
傲寒
傲寒 2020-12-29 02:38

I am writing some vanilla JavaScript to create a nice navigation menu. I am stuck on adding an active class.

I am getting elements by class name NOT by id. The belo

7条回答
  •  失恋的感觉
    2020-12-29 02:53

    getElementsByClassName() returns HTMLCollection so you could try this

    var button = document.getElementsByClassName("navButton")[0];
    

    Edit

    var buttons = document.getElementsByClassName("navButton");
    for(i=0;buttons.length;i++){
       buttons[i].onmouseover = function(){
         this.className += ' active' //add class
         this.setAttribute("src", "images/arrows/top_o.png");
       }
    }
    

提交回复
热议问题