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 below code works if substituted with id, however, I need it to apply to more than one element.
HTML
<img class="navButton" id="topArrow" src="images/arrows/top.png" /> <img class="navButton" id="rightArrow" src="images/arrows/right.png" />
JS
var button = document.getElementsByClassName("navButton"); button.onmouseover = function() { button.setAttribute("class", "active"); button.setAttribute("src", "images/arrows/top_o.png"); }
No answers containing jQuery please.
JavaScript provides 2 different ways by which you can add classes to HTML elements: Using element. classList. add() Method.
Using . className property: This property is used to add a class name to the selected element. Syntax: It is used to set the className property.
You can use Javascript for adding a class: setAttribute and className both method are used to set class (class attribute), these method are not used to adding another class with existing one.
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"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With