How do I add a class to a given element?

I have an element that already has a class:

<div class=someclass>
  <img ... id=image1 name=image1 /> </div> 

Now I want to create a Javascript function that will add a class to the div (not replace, but add).

How can I do that?

Text Copied From
on : Tue, Feb 03, 2009 Views : 1214026

Accepted Answer

Add a space plus the name of your new class to the className property of the element. First, put an id on the element so you can easily get a reference.

<div id=div1 class=someclass>
  <img ... id=image1 name=image1 /> </div> 


var d = document.getElementById(div1);
 d.className +=  otherclass;

See also element.className on MDN.

Text Copied From
on : Tue, Feb 03, 2009

Ask Question

If you want to ask question you must LogIn or SignUp
Login SignUp

Quick Links



Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..


Login to Open ESchool OR Create your account    Login   SignUp