How to add a class to a given element?
Solution 1
If you're only targeting modern browsers:
Use element.classList.add to add a class:
element.classList.add("my-class");
And element.classList.remove to remove a class:
element.classList.remove("my-class");
If you need to support Internet Explorer 9 or lower:
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>
Then
var d = document.getElementById("div1");
d.className += " otherclass";
Note the space before otherclass
. It's important to include the space otherwise it compromises existing classes that come before it in the class list.
See also element.className on MDN.
Solution 2
The easiest way to do this without any framework is to use element.classList.add method.
var element = document.getElementById("div1");
element.classList.add("otherclass");
Edit: And if you want to remove class from an element -
element.classList.remove("otherclass");
I prefer not having to add any empty space and duplicate entry handling myself (which is required when using the document.className
approach). There are some browser limitations, but you can work around them using polyfills.
Solution 3
find your target element "d" however you wish and then:
d.className += ' additionalClass'; //note the space
you can wrap that in cleverer ways to check pre-existence, and check for space requirements etc..
Solution 4
Add Class
-
Cross Compatible
In the following example we add a
classname
to the<body>
element. This is IE-8 compatible.var a = document.body; a.classList ? a.classList.add('classname') : a.className += ' classname';
This is shorthand for the following..
var a = document.body; if (a.classList) { a.classList.add('wait'); } else { a.className += ' wait'; }
-
Performance
If your more concerned with performance over cross-compatibility you can shorten it to the following which is 4% faster.
var z = document.body; document.body.classList.add('wait');
-
Convenience
Alternatively you could use jQuery but the resulting performance is significantly slower. 94% slower according to jsPerf
$('body').addClass('wait');
Removing the class
-
Performance
Using jQuery selectively is the best method for removing a class if your concerned with performance
var a = document.body, c = ' classname'; $(a).removeClass(c);
-
Without jQuery it's 32% slower
var a = document.body, c = ' classname'; a.className = a.className.replace( c, '' ); a.className = a.className + c;
References
Using Prototype
Element("document.body").ClassNames.add("classname")
Element("document.body").ClassNames.remove("classname")
Element("document.body").ClassNames.set("classname")
Using YUI
YAHOO.util.Dom.hasClass(document.body,"classname")
YAHOO.util.Dom.addClass(document.body,"classname")
YAHOO.util.Dom.removeClass(document.body,"classname")
Solution 5
Another approach to add the class to element using pure JavaScript
For adding class:
document.getElementById("div1").classList.add("classToBeAdded");
For removing class:
document.getElementById("div1").classList.remove("classToBeRemoved");
Comments
-
Blankman about 2 years
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?
-
meouw about 15 years"A library will help with everything else as well" - apart from learning JavaScript
-
rfunduk about 15 yearsWhat does adding a class to a DOM element have to do with learning the language? document.getElementById('div1').className is as much a library related issue as using jQuery to do the same is. The question was "how can I do that", a thoroughly tested library is the sensible answer.
-
meouw about 15 years@thenduks: I'm sure you know that JavaScript !== jQuery. It's a good thing that the answers to this question include library and non library solutions because it is important to know how things work not just the simplest way to accomplish them. You'll notice this question is tagged javascript
-
rfunduk about 15 years@meouw: I agree with you. jQuery is written in JavaScript, however, so I maintain that mentioning to the OP that a library is a good idea is not 'pushing a framework down [his] throat'. That's all.
-
mricci over 11 yearsIt's a shame that this isn't supported prior to IE 10.0 because it's an excellent feature and the easiest solution to an issue I come across often.
-
Alexandre Dieulot about 11 years
if( cn.indexOf( classname ) != -1 ) { return; }
Beware that if you add the class “btn” with the class “btn-info” being already here, this fails. -
Radek almost 11 yearsIt said JavaScript, not jQuery or YUI.
-
wcandillon over 10 yearsA polyfill for classList is available.
-
simon over 10 yearsvery nice, but not supported in IE <= 9 or Safari <=5.0 ... :( (caniuse.com/classlist)
-
willlma about 10 yearselement.classList docs on MDN.
-
bafromca over 9 yearsThat's already been answered several times by other users, including discussions of browser support and shims.
-
Shoaib Chikate over 9 years@bafromca I didn't see that previous answer was given and its my mistake. You can flag this answer
-
Aureliano Far Suau over 9 yearswhat about element.classList[length] = "otherclass"?
-
Dan Dascalescu almost 9 years@ShoaibChikate: you can also delete the answer if you'd like (you'll keep the points). Just trying to reduce clutter on this question; totally up to you.
-
Dan Dascalescu almost 9 yearsThis has already been discussed, including browser support.
-
Dan Dascalescu almost 9 years
indexOf
is a naive solution and has a problem already pointed out. -
Dan Dascalescu almost 9 yearsThis has already been discussed, along with browser support.
-
Wilf over 8 yearsWow thanks :) Will the shorthand version (
a.classList ? ...
) have any speed difference compared to the normal one (if (a.classList) { ....
)? -
Silver Ringvee over 8 yearsThis one seems to be the best one to use, as the ones with space at least feel like hacks - not ment for adding classes...
-
Fez Vrasta over 8 yearsThere's olso
classList.remove()
. Why didn't you used it? it's much faster than jQuery jsperf.com/remove-class-vanilla-vs-jquery -
Adam about 8 years@FezVrasta classList isn't supported before IE 10, which still has a decent market share (+13% on netmarketshare.com).
-
Fez Vrasta about 8 years@Adam he used
classList
for everything except to remove classes, this is why I'm asking it. -
Qadir Hussain almost 8 yearshow to remove this class? is there any method to do this in javaScript,not with jQuery
-
akauppi over 7 years@SilverRingvee A further risk of the space approach is that some other developer might not know it's vital, and remove it in order to clean things up.
-
davidcondrey over 7 years@FezVrasta Under cross compatible I did use .add() but only after checking to see if it is available, hense cross compatible. For remove I did not bother to repeat myself so I did not include as many options.
-
Iulian Onofrei over 7 yearsIsn't
a.className = a.className + c;
adding the class back? I don't get it. -
Iulian Onofrei over 7 years
-
eltiare over 7 years@QadirHussain: You have to parse the string manually and then assign it to className.
-
I Like about 7 yearshow to do in javascript with multiple elements?
-
Michael Tontchev about 7 yearsIn what sense do you need to handle duplicates? In removal? You can use classList.remove(...) in that case, but you can still use className to add.
-
Return-1 over 6 yearsadding a class like so doesnt trigger transitions for me.. is this a known issue or?
-
DeathGrip over 6 yearsAnd to remove using this method?
-
TheTechy over 6 years@DeathGrip simply set the class back to a single defined name d.className = 'originalClass';
-
Amir Fo over 5 yearsyou should use
element.className.split(" ");
to prevent the problem @AlexandreDieulot reported here. -
belvederef over 5 yearsIt's important to note that using this method will add the class as many times as the line
d.className += " otherclass"
is called. That may or may not be the desired outcome. Check out the second most voted answer for adding a class only once. -
Eugen Konkov over 5 yearsThe answer below show more elegant way to deal with
classList
-
Ishmael over 5 yearsI agree that @Yuri's answer should be the accepted answer.
-
Mark Schultheiss about 5 years@TheTechy - if you have more than one class you need to keep (which happens a lot these days), that will not work.
-
Eric Soyke almost 5 yearsAnd don't forget that leading space! ;)
-
Stijn de Witt over 4 yearsDownvoted, not because it is a bad answer, but there is a better way nowadays using
element.classList.add
as discussed in this answer -
Stijn de Witt over 4 yearsTo remove the old-fashioned way,
split
the classname on whitespace, remove the one you don't want from the resulting array, thenjoin
the array again... or useelement.classList.remove
. -
Stijn de Witt over 4 yearsThis should be the accepted answer in 2019 and beyond.
-
Nabi K.A.Z. over 4 yearsFor multiple classes:
element.classList.add("one", "tow", ...);
-
NomanJaved over 4 yearshow can we do this with
getElementByClassName
-
jave.web about 4 yearsUnless your job requires it specifically, please don't support IE9 and lower :)
-
staminna over 3 yearshow about to target the last class instead?
-
Timo almost 2 yearsplus one for adding more than one class.
-
Kröw almost 2 years@rfunduk Your thoroughly tested library is a way to avoid a sensible answer.