How to add a class to a given element?
Asked Answered
Y

28

1693

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?

Yeomanry answered 3/2, 2009 at 13:54 Comment(1)
To anyone reading this thread in 2020 or later, skip the old className method and use element.classList.add("my-class") instead.Scandent
S
2747

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.

Shari answered 3/2, 2009 at 13:58 Comment(14)
If the only work on the whole page that needs to be done with JavaScript is this class name addition, then yes. But I can't see this being the only dynamic part of the page. A library will help with everything else as well. At 30-50kb jQuery is hardly a hit worth discussing.Verst
"A library will help with everything else as well" - apart from learning JavaScriptExult
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.Verst
@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 javascriptExult
@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.Verst
how to remove this class? is there any method to do this in javaScript,not with jQueryParaplegia
@QadirHussain: You have to parse the string manually and then assign it to className.Clipped
how to do in javascript with multiple elements?Cythera
adding a class like so doesnt trigger transitions for me.. is this a known issue or?Vaccaro
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.Esta
And don't forget that leading space! ;)Mercado
Downvoted, not because it is a bad answer, but there is a better way nowadays using element.classList.add as discussed in this answerCampfire
Unless your job requires it specifically, please don't support IE9 and lower :)Tragicomedy
@Verst Your thoroughly tested library is a way to avoid a sensible answer.Flintlock
C
1409

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.

Chou answered 31/12, 2012 at 12:12 Comment(10)
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.Jitney
A polyfill for classList is available.Recycle
element.classList docs on MDN.Redden
what about element.classList[length] = "otherclass"?Jupon
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...Victorious
@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.Lovash
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.Comportment
This should be the accepted answer in 2019 and beyond.Campfire
For multiple classes: element.classList.add("one", "tow", ...);Brickle
how can we do this with getElementByClassNameLydell
O
189

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..

Outlaw answered 3/2, 2009 at 14:1 Comment(4)
And to remove using this method?Crowson
@Crowson simply set the class back to a single defined name d.className = 'originalClass';Fledgling
@Fledgling - if you have more than one class you need to keep (which happens a lot these days), that will not work.Wilie
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.Campfire
C
149

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")
Colorfast answered 22/12, 2014 at 23:29 Comment(7)
Wow thanks :) Will the shorthand version (a.classList ? ...) have any speed difference compared to the normal one (if (a.classList) { ....)?Parvenu
There's olso classList.remove(). Why didn't you used it? it's much faster than jQuery jsperf.com/remove-class-vanilla-vs-jqueryDincolo
@FezVrasta classList isn't supported before IE 10, which still has a decent market share (+13% on netmarketshare.com).Arvid
@Arvid he used classList for everything except to remove classes, this is why I'm asking it.Dincolo
@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.Colorfast
Isn't a.className = a.className + c; adding the class back? I don't get it.Globular
And it looks like DOMTokenList has a remove method too.Globular
P
47

2 different ways to add class using JavaScript

JavaScript provides 2 different ways by which you can add classes to HTML elements:

  1. Using element.classList.add() Method
  2. Using className property

Using both methods you can add single or multiple classes at once.

1. Using element.classList.add() Method

var element = document.querySelector('.box');
// using add method
// adding single class
element.classList.add('color');

// adding multiple class
element.classList.add('border', 'shadow');
.box {
    width: 200px;
    height: 100px;
}
.color {
    background: skyblue;
}
.border {
    border: 2px solid black;
}
.shadow {
    box-shadow: 5px 5px 5px gray;
}
<div class="box">My Box</div>

2. Using element.className Property

Note: Always use += operator and add a space before class name to add class with classList method.

var element = document.querySelector('.box');
// using className Property
// adding single class
element.className += ' color';

// adding multiple class
// keep classes space separated
element.className += ' border shadow';
.box {
    width: 200px;
    height: 100px;
}
.color {
    background: skyblue;
}
.border {
    border: 2px solid black;
}
.shadow {
    box-shadow: 5px 5px 5px gray;
}
<div class="box">My Box</div>
Perfect answered 7/11, 2021 at 2:35 Comment(1)
plus one for adding more than one class.Diseur
R
38

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");
Rubinrubina answered 23/9, 2014 at 11:15 Comment(3)
That's already been answered several times by other users, including discussions of browser support and shims.Leveloff
@Leveloff I didn't see that previous answer was given and its my mistake. You can flag this answerRubinrubina
@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.Platyhelminth
S
27
document.getElementById('some_id').className+='  someclassname'

OR:

document.getElementById('some_id').classList.add('someclassname')

First approach helped in adding the class when second approach didn't work.
Don't forget to keep a space in front of the ' someclassname' in the first approach.

For removal you can use:

document.getElementById('some_id').classList.remove('someclassname')
Smite answered 29/5, 2020 at 6:31 Comment(0)
E
25

When the work I'm doing doesn't warrant using a library, I use these two functions:

function addClass( classname, element ) {
    var cn = element.className;
    //test for existance
    if( cn.indexOf( classname ) != -1 ) {
        return;
    }
    //add a space if the element already has class
    if( cn != '' ) {
        classname = ' '+classname;
    }
    element.className = cn+classname;
}

function removeClass( classname, element ) {
    var cn = element.className;
    var rxp = new RegExp( "\\s?\\b"+classname+"\\b", "g" );
    cn = cn.replace( rxp, '' );
    element.className = cn;
}
Exult answered 3/2, 2009 at 14:40 Comment(2)
if( cn.indexOf( classname ) != -1 ) { return; } Beware that if you add the class “btn” with the class “btn-info” being already here, this fails.Peart
you should use element.className.split(" "); to prevent the problem @AlexandreDieulot reported here.Effluence
V
24

Assuming you're doing more than just adding this one class (eg, you've got asynchronous requests and so on going on as well), I'd recommend a library like Prototype or jQuery.

This will make just about everything you'll need to do (including this) very simple.

So let's say you've got jQuery on your page now, you could use code like this to add a class name to an element (on load, in this case):

$(document).ready( function() {
  $('#div1').addClass( 'some_other_class' );
} );

Check out the jQuery API browser for other stuff.

Verst answered 3/2, 2009 at 14:0 Comment(0)
I
18

You can use the classList.add OR classList.remove method to add/remove a class from a element.

var nameElem = document.getElementById("name")
nameElem.classList.add("anyclss")

The above code will add(and NOT replace) a class "anyclass" to nameElem. Similarly you can use classList.remove() method to remove a class.

nameElem.classList.remove("anyclss")
Interdental answered 10/8, 2013 at 8:59 Comment(2)
very nice, but not supported in IE <= 9 or Safari <=5.0 ... :( (caniuse.com/classlist)Richmond
This has already been discussed, including browser support.Platyhelminth
B
13

To add an additional class to an element:

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:

document.getElementById("MyElement").className += " MyClass";

To change all classes for an element:

To replace all existing classes with one or more new classes, set the className attribute:

document.getElementById("MyElement").className = "MyClass";

(You can use a space-delimited list to apply multiple classes.)

Bookstand answered 20/8, 2015 at 8:38 Comment(0)
P
9

This might be helpful for WordPress developers etc.

document.querySelector('[data-section="section-hb-button-1"] .ast-custom-button').classList.add('TryMyClass');
Paracelsus answered 23/8, 2022 at 18:13 Comment(0)
K
8

If you don't want to use jQuery and want to support older browsers:

function addClass(elem, clazz) {
    if (!elemHasClass(elem, clazz)) {
        elem.className += " " + clazz;
    }
}

function elemHasClass(elem, clazz) {
    return new RegExp("( |^)" + clazz + "( |$)").test(elem.className);
}
Keelykeen answered 31/3, 2016 at 23:29 Comment(0)
S
8

I too think that the fastest way is to use Element.prototype.classList as in es5: document.querySelector(".my.super-class").classList.add('new-class') but in ie8 there is no such thing as Element.prototype.classList, anyway you can polyfill it with this snippet (fell free to edit and improve it):

if(Element.prototype.classList === void 0){
	function DOMTokenList(classes, self){
		typeof classes == "string" && (classes = classes.split(' '))
		while(this.length){
			Array.prototype.pop.apply(this);
		}
		Array.prototype.push.apply(this, classes);
		this.__self__ = this.__self__ || self
	}

	DOMTokenList.prototype.item = function (index){
		return this[index];
	}

	DOMTokenList.prototype.contains = function (myClass){
		for(var i = this.length - 1; i >= 0 ; i--){
			if(this[i] === myClass){
				return true;
			}
		}
		return false
	}

	DOMTokenList.prototype.add = function (newClass){
		if(this.contains(newClass)){
			return;
		}
		this.__self__.className += (this.__self__.className?" ":"")+newClass;
		DOMTokenList.call(this, this.__self__.className)
	}

	DOMTokenList.prototype.remove = function (oldClass){
		if(!this.contains(newClass)){
			return;
		}
		this[this.indexOf(oldClass)] = undefined
		this.__self__.className = this.join(' ').replace(/  +/, ' ')
		DOMTokenList.call(this, this.__self__.className)
	}

	DOMTokenList.prototype.toggle = function (aClass){
		this[this.contains(aClass)? 'remove' : 'add'](aClass)
		return this.contains(aClass);
	}

	DOMTokenList.prototype.replace = function (oldClass, newClass){
		this.contains(oldClass) && this.remove(oldClass) && this.add(newClass)
	}

	Object.defineProperty(Element.prototype, 'classList', {
		get: function() {
			return new DOMTokenList( this.className, this );
		},
		enumerable: false
	})
}
Studnia answered 30/12, 2017 at 17:46 Comment(0)
H
7

To add, remove or check element classes in a simple way:

var uclass = {
    exists: function(elem,className){var p = new RegExp('(^| )'+className+'( |$)');return (elem.className && elem.className.match(p));},
    add: function(elem,className){if(uclass.exists(elem,className)){return true;}elem.className += ' '+className;},
    remove: function(elem,className){var c = elem.className;var p = new RegExp('(^| )'+className+'( |$)');c = c.replace(p,' ').replace(/  /g,' ');elem.className = c;}
};

var elem = document.getElementById('someElem');
//Add a class, only if not exists yet.
uclass.add(elem,'someClass');
//Remove class
uclass.remove(elem,'someClass');
Hurd answered 11/6, 2014 at 8:11 Comment(0)
C
7

You can use modern approach similar to jQuery

If you need to change only one element, first one that JS will find in DOM, you can use this:

document.querySelector('.someclass').className += " red";
.red {
  color: red;
}
<div class="someclass">
  <p>This method will add class "red" only to first element in DOM</p>
</div>

<div class="someclass">
  <p>lorem ipsum</p>
</div>

<div class="someclass">
  <p>lorem ipsum</p>
</div>

<div class="someclass">
  <p>lorem ipsum</p>
</div>

Keep in mind to leave one space before class name.

If you have multiple classes where you want to add new class, you can use it like this

document.querySelectorAll('.someclass').forEach(function(element) {
  element.className += " red";
});
.red {
  color: red;
}
<div class="someclass">
  <p>This method will add class "red" to all elements in DOM that have "someclass" class.</p>
</div>

<div class="someclass">
  <p>lorem ipsum</p>
</div>

<div class="someclass">
  <p>lorem ipsum</p>
</div>

<div class="someclass">
  <p>lorem ipsum</p>
</div>
Clientele answered 24/9, 2017 at 15:44 Comment(1)
how about to target the last class instead?Plossl
D
6

I know IE9 is shutdown officially and we can achieve it with element.classList as many told above but I just tried to learn how it works without classList with help of many answers above I could learn it.

Below code extends many answers above and improves them by avoiding adding duplicate classes.

function addClass(element,className){
  var classArray = className.split(' ');
  classArray.forEach(function (className) {
    if(!hasClass(element,className)){
      element.className += " "+className;
    }
  });            
}
//this will add 5 only once
addClass(document.querySelector('#getbyid'),'3 4 5 5 5');
Degraw answered 18/12, 2016 at 17:30 Comment(0)
A
5

Just to elaborate on what others have said, multiple CSS classes are combined in a single string, delimited by spaces. Thus, if you wanted to hard-code it, it would simply look like this:

<div class="someClass otherClass yetAnotherClass">
      <img ... id="image1" name="image1" />
</div>

From there you can easily derive the javascript necessary to add a new class... just append a space followed by the new class to the element's className property. Knowing this, you can also write a function to remove a class later should the need arise.

Autodidact answered 3/2, 2009 at 14:18 Comment(0)
D
5

I think it's better to use pure JavaScript, which we can run on the DOM of the Browser.

Here is the functional way to use it. I have used ES6 but feel free to use ES5 and function expression or function definition, whichever suits your JavaScript StyleGuide.

'use strict'

const oldAdd = (element, className) => {
  let classes = element.className.split(' ')
  if (classes.indexOf(className) < 0) {
    classes.push(className)
  }
  element.className = classes.join(' ')
}

const oldRemove = (element, className) => {
  let classes = element.className.split(' ')
  const idx = classes.indexOf(className)
  if (idx > -1) {
    classes.splice(idx, 1)
  }
  element.className = classes.join(' ')
}

const addClass = (element, className) => {
  if (element.classList) {
    element.classList.add(className)
  } else {
    oldAdd(element, className)
  }
}

const removeClass = (element, className) => {
  if (element.classList) {
    element.classList.remove(className)
  } else {
    oldRemove(element, className)
  }
}
Dripstone answered 28/11, 2016 at 0:41 Comment(0)
S
3

Sample with pure JS. In first example we get our element's id and add e.g. 2 classes.

document.addEventListener('DOMContentLoaded', function() {
    document.getElementsById('tabGroup').className = "anyClass1 anyClass2";
})

In second example we get element's class name and add 1 more.

document.addEventListener('DOMContentLoaded', function() {
    document.getElementsByClassName('tabGroup')[0].className = "tabGroup ready";
})
Scherle answered 19/7, 2015 at 16:31 Comment(0)
A
3

For those using Lodash and wanting to update className string:

// get element reference
var elem = document.getElementById('myElement');

// add some classes. Eg. 'nav' and 'nav header'
elem.className = _.chain(elem.className).split(/[\s]+/).union(['nav','navHeader']).join(' ').value()

// remove the added classes
elem.className = _.chain(elem.className).split(/[\s]+/).difference(['nav','navHeader']).join(' ').value()
Architectonic answered 30/6, 2017 at 7:21 Comment(0)
D
3

The majority of people use a .classList.add on a getElementById, but I i wanted to use it on a getElementByClassName. To do that, i was using a forEach like this :

document.getElementsByClassName("class-name").forEach(element => element.classList.add("new-class"));

But it didn't work because i discovered that getElementsByClassName returns a HTML collection and not an array. To handle that I converted it to an array with this code :

[...document.getElementsByClassName("class-name")].forEach(element => element.classList.add("new-class"));

Dispensable answered 3/2, 2023 at 11:1 Comment(0)
R
2

Shortest

image1.parentNode.className+=' box';

image1.parentNode.className+=' box';
.box { width: 100px; height:100px; background: red; }
<div class="someclass">
    <img ... id="image1" name="image1" />
</div>
Redfield answered 14/5, 2020 at 11:20 Comment(0)
D
1

You can use the API querySelector to select your element and then create a function with the element and the new classname as parameters. Using classlist for modern browsers, else for IE8. Then you can call the function after an event.

 //select the dom element
 var addClassVar = document.querySelector('.someclass');

 //define the addclass function
 var addClass = function(el,className){
   if (el.classList){
     el.classList.add(className);
   }
   else {
     el.className += ' ' + className;
  }
};

//call the function
addClass(addClassVar, 'newClass');
Darvon answered 6/3, 2015 at 10:27 Comment(1)
This has already been discussed, along with browser support.Platyhelminth
S
1

In my case, I had more than one class called main-wrapper in the DOM, but I only wanted to affect the parent main-wrapper. Using :first Selector (https://api.jquery.com/first-selector/), I could select the first matched DOM element. This was the solution for me:

$(document).ready( function() {
    $('.main-wrapper:first').addClass('homepage-redesign');
    $('#deals-index > div:eq(0) > div:eq(1)').addClass('doubleheaderredesign');
} );

I also did the same thing for the second children of a specific div in my DOM as you can see in the code where I used $('#deals-index > div:eq(0) > div:eq(1)').addClass('doubleheaderredesign');.

NOTE: I used jQuery as you can see.

Shrum answered 18/8, 2020 at 2:41 Comment(0)
P
0

first, give the div an id. Then, call function appendClass:

<script language="javascript">
  function appendClass(elementId, classToAppend){
    var oldClass = document.getElementById(elementId).getAttribute("class");
    if (oldClass.indexOf(classToAdd) == -1)
    {
      document.getElementById(elementId).setAttribute("class", classToAppend);
    }
}
</script>
Petunia answered 3/2, 2009 at 14:4 Comment(2)
it will replace the class not append ! Maybe be a line is missing or a oldClass+" "+classToAppend instead of the last classToAppendAscarid
indexOf is a naive solution and has a problem already pointed out.Platyhelminth
C
-4

This js code works for me

provides classname replacement

var DDCdiv = hEle.getElementBy.....

var cssCNs = DDCdiv.getAttribute('class');
var Ta = cssCNs.split(' '); //split into an array
for (var i=0; i< Ta.length;i++)
{
    if (Ta[i] == 'visible'){
        Ta[i] = 'hidden';
        break;// quit for loop
    }
    else if (Ta[i] == 'hidden'){
        Ta[i] = 'visible';
    break;// quit for loop
    }
}
DDCdiv.setAttribute('class',Ta.join(' ') );  // Join array with space and set class name

To add just use

var cssCNs = DDCdiv.getAttribute('class');
var Ta = cssCNs.split(' '); //split into an array
Ta.push('New class name');
// Ta.push('Another class name');//etc...
DDCdiv.setAttribute('class',Ta.join(' ') );  // Join array with space and set class name

To remove use

var cssCNs = DDCdiv.getAttribute('class');
var Ta = cssCNs.split(' '); //split into an array

for (var i=0; i< Ta.length;i++)
{
    if (Ta[i] == 'visible'){
        Ta.splice( i, 1 );
        break;// quit for loop
    }
}
DDCdiv.setAttribute('class',Ta.join(' ') );  // Join array with space and set class name

Hope this is helpful to sombody

Covell answered 27/6, 2014 at 14:48 Comment(0)
O
-11

In YUI, if you include yuidom, you can use

YAHOO.util.Dom.addClass('div1','className');

HTH

Osmium answered 3/2, 2009 at 14:11 Comment(1)
It said JavaScript, not jQuery or YUI.Airplane

© 2022 - 2024 — McMap. All rights reserved.