How to add a class to a given element?

2,000,329

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

  1. jsPerf Test Case: Adding a Class
  2. jsPerf Test Case: Removing a Class

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");
Share:
2,000,329
Blankman
Author by

Blankman

... .. . blank

Updated on February 17, 2022

Comments

  • Blankman
    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
    meouw about 15 years
    "A library will help with everything else as well" - apart from learning JavaScript
  • rfunduk
    rfunduk about 15 years
    What 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
    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
    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
    mricci over 11 years
    It'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
    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
    Radek almost 11 years
    It said JavaScript, not jQuery or YUI.
  • wcandillon
    wcandillon over 10 years
    A polyfill for classList is available.
  • simon
    simon over 10 years
    very nice, but not supported in IE <= 9 or Safari <=5.0 ... :( (caniuse.com/classlist)
  • willlma
    willlma about 10 years
  • bafromca
    bafromca over 9 years
    That's already been answered several times by other users, including discussions of browser support and shims.
  • Shoaib Chikate
    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
    Aureliano Far Suau over 9 years
    what about element.classList[length] = "otherclass"?
  • Dan Dascalescu
    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
    Dan Dascalescu almost 9 years
    This has already been discussed, including browser support.
  • Dan Dascalescu
    Dan Dascalescu almost 9 years
    indexOf is a naive solution and has a problem already pointed out.
  • Dan Dascalescu
    Dan Dascalescu almost 9 years
    This has already been discussed, along with browser support.
  • Wilf
    Wilf over 8 years
    Wow thanks :) Will the shorthand version (a.classList ? ...) have any speed difference compared to the normal one (if (a.classList) { ....)?
  • Silver Ringvee
    Silver Ringvee over 8 years
    This 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
    Fez Vrasta over 8 years
    There's olso classList.remove(). Why didn't you used it? it's much faster than jQuery jsperf.com/remove-class-vanilla-vs-jquery
  • Adam
    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
    Fez Vrasta about 8 years
    @Adam he used classList for everything except to remove classes, this is why I'm asking it.
  • Qadir Hussain
    Qadir Hussain almost 8 years
    how to remove this class? is there any method to do this in javaScript,not with jQuery
  • akauppi
    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
    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
    Iulian Onofrei over 7 years
    Isn't a.className = a.className + c; adding the class back? I don't get it.
  • Iulian Onofrei
    Iulian Onofrei over 7 years
    And it looks like DOMTokenList has a remove method too.
  • eltiare
    eltiare over 7 years
    @QadirHussain: You have to parse the string manually and then assign it to className.
  • I Like
    I Like about 7 years
    how to do in javascript with multiple elements?
  • Michael Tontchev
    Michael Tontchev about 7 years
    In 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
    Return-1 over 6 years
    adding a class like so doesnt trigger transitions for me.. is this a known issue or?
  • DeathGrip
    DeathGrip over 6 years
    And to remove using this method?
  • TheTechy
    TheTechy over 6 years
    @DeathGrip simply set the class back to a single defined name d.className = 'originalClass';
  • Amir Fo
    Amir Fo over 5 years
    you should use element.className.split(" "); to prevent the problem @AlexandreDieulot reported here.
  • belvederef
    belvederef over 5 years
    It'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
    Eugen Konkov over 5 years
    The answer below show more elegant way to deal with classList
  • Ishmael
    Ishmael over 5 years
    I agree that @Yuri's answer should be the accepted answer.
  • Mark Schultheiss
    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
    Eric Soyke almost 5 years
    And don't forget that leading space! ;)
  • Stijn de Witt
    Stijn de Witt over 4 years
    Downvoted, 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
    Stijn de Witt over 4 years
    To remove the old-fashioned way, split the classname on whitespace, remove the one you don't want from the resulting array, then join the array again... or use element.classList.remove.
  • Stijn de Witt
    Stijn de Witt over 4 years
    This should be the accepted answer in 2019 and beyond.
  • Nabi K.A.Z.
    Nabi K.A.Z. over 4 years
    For multiple classes: element.classList.add("one", "tow", ...);
  • NomanJaved
    NomanJaved over 4 years
    how can we do this with getElementByClassName
  • jave.web
    jave.web about 4 years
    Unless your job requires it specifically, please don't support IE9 and lower :)
  • staminna
    staminna over 3 years
    how about to target the last class instead?
  • Timo
    Timo almost 2 years
    plus one for adding more than one class.
  • Kröw
    Kröw almost 2 years
    @rfunduk Your thoroughly tested library is a way to avoid a sensible answer.