add class with JavaScript

前端 未结 7 2055
傲寒
傲寒 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:58

    document.getElementsByClassName returns a node list. So you'll have to iterate over the list and bind the event to individual elements. Like this...

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

提交回复
热议问题