Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add class with JavaScript

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.

like image 926
vincentieo Avatar asked Jul 30 '13 10:07

vincentieo


People also ask

Can you add a class in JavaScript?

JavaScript provides 2 different ways by which you can add classes to HTML elements: Using element. classList. add() Method.

How do you add a class to an element?

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.

How do I add a class dynamically?

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.


1 Answers

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");     } } 
like image 193
mohkhan Avatar answered Oct 13 '22 09:10

mohkhan