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?
This question is related to
javascript
dom-manipulation
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");
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.
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";
_x000D_
.red {_x000D_
color: red;_x000D_
}
_x000D_
<div class="someclass">_x000D_
<p>This method will add class "red" only to first element in DOM</p>_x000D_
</div>_x000D_
_x000D_
<div class="someclass">_x000D_
<p>lorem ipsum</p>_x000D_
</div>_x000D_
_x000D_
<div class="someclass">_x000D_
<p>lorem ipsum</p>_x000D_
</div>_x000D_
_x000D_
<div class="someclass">_x000D_
<p>lorem ipsum</p>_x000D_
</div>
_x000D_
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) {_x000D_
element.className += " red";_x000D_
});
_x000D_
.red {_x000D_
color: red;_x000D_
}
_x000D_
<div class="someclass">_x000D_
<p>This method will add class "red" to all elements in DOM that have "someclass" class.</p>_x000D_
</div>_x000D_
_x000D_
<div class="someclass">_x000D_
<p>lorem ipsum</p>_x000D_
</div>_x000D_
_x000D_
<div class="someclass">_x000D_
<p>lorem ipsum</p>_x000D_
</div>_x000D_
_x000D_
<div class="someclass">_x000D_
<p>lorem ipsum</p>_x000D_
</div>
_x000D_
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");
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..
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.
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;
}
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'_x000D_
_x000D_
const oldAdd = (element, className) => {_x000D_
let classes = element.className.split(' ')_x000D_
if (classes.indexOf(className) < 0) {_x000D_
classes.push(className)_x000D_
}_x000D_
element.className = classes.join(' ')_x000D_
}_x000D_
_x000D_
const oldRemove = (element, className) => {_x000D_
let classes = element.className.split(' ')_x000D_
const idx = classes.indexOf(className)_x000D_
if (idx > -1) {_x000D_
classes.splice(idx, 1)_x000D_
}_x000D_
element.className = classes.join(' ')_x000D_
}_x000D_
_x000D_
const addClass = (element, className) => {_x000D_
if (element.classList) {_x000D_
element.classList.add(className)_x000D_
} else {_x000D_
oldAdd(element, className)_x000D_
}_x000D_
}_x000D_
_x000D_
const removeClass = (element, className) => {_x000D_
if (element.classList) {_x000D_
element.classList.remove(className)_x000D_
} else {_x000D_
oldRemove(element, className)_x000D_
}_x000D_
}
_x000D_
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>
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;
}
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');
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")
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>
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
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..
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.
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()
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>
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){_x000D_
function DOMTokenList(classes, self){_x000D_
typeof classes == "string" && (classes = classes.split(' '))_x000D_
while(this.length){_x000D_
Array.prototype.pop.apply(this);_x000D_
}_x000D_
Array.prototype.push.apply(this, classes);_x000D_
this.__self__ = this.__self__ || self_x000D_
}_x000D_
_x000D_
DOMTokenList.prototype.item = function (index){_x000D_
return this[index];_x000D_
}_x000D_
_x000D_
DOMTokenList.prototype.contains = function (myClass){_x000D_
for(var i = this.length - 1; i >= 0 ; i--){_x000D_
if(this[i] === myClass){_x000D_
return true;_x000D_
}_x000D_
}_x000D_
return false_x000D_
}_x000D_
_x000D_
DOMTokenList.prototype.add = function (newClass){_x000D_
if(this.contains(newClass)){_x000D_
return;_x000D_
}_x000D_
this.__self__.className += (this.__self__.className?" ":"")+newClass;_x000D_
DOMTokenList.call(this, this.__self__.className)_x000D_
}_x000D_
_x000D_
DOMTokenList.prototype.remove = function (oldClass){_x000D_
if(!this.contains(newClass)){_x000D_
return;_x000D_
}_x000D_
this[this.indexOf(oldClass)] = undefined_x000D_
this.__self__.className = this.join(' ').replace(/ +/, ' ')_x000D_
DOMTokenList.call(this, this.__self__.className)_x000D_
}_x000D_
_x000D_
DOMTokenList.prototype.toggle = function (aClass){_x000D_
this[this.contains(aClass)? 'remove' : 'add'](aClass)_x000D_
return this.contains(aClass);_x000D_
}_x000D_
_x000D_
DOMTokenList.prototype.replace = function (oldClass, newClass){_x000D_
this.contains(oldClass) && this.remove(oldClass) && this.add(newClass)_x000D_
}_x000D_
_x000D_
Object.defineProperty(Element.prototype, 'classList', {_x000D_
get: function() {_x000D_
return new DOMTokenList( this.className, this );_x000D_
},_x000D_
enumerable: false_x000D_
})_x000D_
}
_x000D_
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";
})
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")
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');
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');
image1.parentNode.className+=' box';
image1.parentNode.className+=' box';
_x000D_
.box { width: 100px; height:100px; background: red; }
_x000D_
<div class="someclass">_x000D_
<img ... id="image1" name="image1" />_x000D_
</div>
_x000D_
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');
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')
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;
}
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 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.)
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.
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){_x000D_
function DOMTokenList(classes, self){_x000D_
typeof classes == "string" && (classes = classes.split(' '))_x000D_
while(this.length){_x000D_
Array.prototype.pop.apply(this);_x000D_
}_x000D_
Array.prototype.push.apply(this, classes);_x000D_
this.__self__ = this.__self__ || self_x000D_
}_x000D_
_x000D_
DOMTokenList.prototype.item = function (index){_x000D_
return this[index];_x000D_
}_x000D_
_x000D_
DOMTokenList.prototype.contains = function (myClass){_x000D_
for(var i = this.length - 1; i >= 0 ; i--){_x000D_
if(this[i] === myClass){_x000D_
return true;_x000D_
}_x000D_
}_x000D_
return false_x000D_
}_x000D_
_x000D_
DOMTokenList.prototype.add = function (newClass){_x000D_
if(this.contains(newClass)){_x000D_
return;_x000D_
}_x000D_
this.__self__.className += (this.__self__.className?" ":"")+newClass;_x000D_
DOMTokenList.call(this, this.__self__.className)_x000D_
}_x000D_
_x000D_
DOMTokenList.prototype.remove = function (oldClass){_x000D_
if(!this.contains(newClass)){_x000D_
return;_x000D_
}_x000D_
this[this.indexOf(oldClass)] = undefined_x000D_
this.__self__.className = this.join(' ').replace(/ +/, ' ')_x000D_
DOMTokenList.call(this, this.__self__.className)_x000D_
}_x000D_
_x000D_
DOMTokenList.prototype.toggle = function (aClass){_x000D_
this[this.contains(aClass)? 'remove' : 'add'](aClass)_x000D_
return this.contains(aClass);_x000D_
}_x000D_
_x000D_
DOMTokenList.prototype.replace = function (oldClass, newClass){_x000D_
this.contains(oldClass) && this.remove(oldClass) && this.add(newClass)_x000D_
}_x000D_
_x000D_
Object.defineProperty(Element.prototype, 'classList', {_x000D_
get: function() {_x000D_
return new DOMTokenList( this.className, this );_x000D_
},_x000D_
enumerable: false_x000D_
})_x000D_
}
_x000D_
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.
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";
})
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
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'_x000D_
_x000D_
const oldAdd = (element, className) => {_x000D_
let classes = element.className.split(' ')_x000D_
if (classes.indexOf(className) < 0) {_x000D_
classes.push(className)_x000D_
}_x000D_
element.className = classes.join(' ')_x000D_
}_x000D_
_x000D_
const oldRemove = (element, className) => {_x000D_
let classes = element.className.split(' ')_x000D_
const idx = classes.indexOf(className)_x000D_
if (idx > -1) {_x000D_
classes.splice(idx, 1)_x000D_
}_x000D_
element.className = classes.join(' ')_x000D_
}_x000D_
_x000D_
const addClass = (element, className) => {_x000D_
if (element.classList) {_x000D_
element.classList.add(className)_x000D_
} else {_x000D_
oldAdd(element, className)_x000D_
}_x000D_
}_x000D_
_x000D_
const removeClass = (element, className) => {_x000D_
if (element.classList) {_x000D_
element.classList.remove(className)_x000D_
} else {_x000D_
oldRemove(element, className)_x000D_
}_x000D_
}
_x000D_
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>
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.
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..
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')
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.
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";
_x000D_
.red {_x000D_
color: red;_x000D_
}
_x000D_
<div class="someclass">_x000D_
<p>This method will add class "red" only to first element in DOM</p>_x000D_
</div>_x000D_
_x000D_
<div class="someclass">_x000D_
<p>lorem ipsum</p>_x000D_
</div>_x000D_
_x000D_
<div class="someclass">_x000D_
<p>lorem ipsum</p>_x000D_
</div>_x000D_
_x000D_
<div class="someclass">_x000D_
<p>lorem ipsum</p>_x000D_
</div>
_x000D_
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) {_x000D_
element.className += " red";_x000D_
});
_x000D_
.red {_x000D_
color: red;_x000D_
}
_x000D_
<div class="someclass">_x000D_
<p>This method will add class "red" to all elements in DOM that have "someclass" class.</p>_x000D_
</div>_x000D_
_x000D_
<div class="someclass">_x000D_
<p>lorem ipsum</p>_x000D_
</div>_x000D_
_x000D_
<div class="someclass">_x000D_
<p>lorem ipsum</p>_x000D_
</div>_x000D_
_x000D_
<div class="someclass">_x000D_
<p>lorem ipsum</p>_x000D_
</div>
_x000D_
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');
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;
Element("document.body").ClassNames.add("classname")
Element("document.body").ClassNames.remove("classname")
Element("document.body").ClassNames.set("classname")
YAHOO.util.Dom.hasClass(document.body,"classname")
YAHOO.util.Dom.addClass(document.body,"classname")
YAHOO.util.Dom.removeClass(document.body,"classname")
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");
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.
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');
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;
Element("document.body").ClassNames.add("classname")
Element("document.body").ClassNames.remove("classname")
Element("document.body").ClassNames.set("classname")
YAHOO.util.Dom.hasClass(document.body,"classname")
YAHOO.util.Dom.addClass(document.body,"classname")
YAHOO.util.Dom.removeClass(document.body,"classname")
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');
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;
}
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 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.)
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);
}
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');
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.
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()
image1.parentNode.className+=' box';
image1.parentNode.className+=' box';
_x000D_
.box { width: 100px; height:100px; background: red; }
_x000D_
<div class="someclass">_x000D_
<img ... id="image1" name="image1" />_x000D_
</div>
_x000D_
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.
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.
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..
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.
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);
}
Source: Stackoverflow.com