Changing class using JavaScript [duplicate] - javascript

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?

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.

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.

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

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
jsPerf Test Case: Adding a Class
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")

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");

2 different ways to add class using JavaScript
JavaScript provides 2 different ways by which you can add classes to HTML elements:
Using element.classList.add() Method
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
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>

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;
}

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.

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

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);
}

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
})
}

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');

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

This might be helpful for WordPress developers etc.
document.querySelector('[data-section="section-hb-button-1"] .ast-custom-button').classList.add('TryMyClass');

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.

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)
}
}

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";
})

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()

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>

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');

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.

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"));

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

In YUI, if you include yuidom, you can use
YAHOO.util.Dom.addClass('div1','className');
HTH

Related

Add a number to each element with the same class [duplicate]

How can I change the class of an HTML element in response to an onclick or any other events using JavaScript?
Modern HTML5 Techniques for changing classes
Modern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library:
document.getElementById("MyElement").classList.add('MyClass');
document.getElementById("MyElement").classList.remove('MyClass');
if ( document.getElementById("MyElement").classList.contains('MyClass') )
document.getElementById("MyElement").classList.toggle('MyClass');
Unfortunately, these do not work in Internet Explorer prior to v10, though there is a shim to add support for it to IE8 and IE9, available from this page. It is, though, getting more and more supported.
Simple cross-browser solution
The standard JavaScript way to select an element is using document.getElementById("Id"), which is what the following examples use - you can of course obtain elements in other ways, and in the right situation may simply use this instead - however, going into detail on this is beyond the scope of the answer.
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.)
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 remove a class from an element:
To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:
document.getElementById("MyElement").className =
document.getElementById("MyElement").className.replace
( /(?:^|\s)MyClass(?!\S)/g , '' )
/* Code wrapped for readability - above is all one statement */
An explanation of this regex is as follows:
(?:^|\s) # Match the start of the string or any single whitespace character
MyClass # The literal text for the classname to remove
(?!\S) # Negative lookahead to verify the above is the whole classname
# Ensures there is no non-space character following
# (i.e. must be the end of the string or space)
The g flag tells the replace to repeat as required, in case the class name has been added multiple times.
To check if a class is already applied to an element:
The same regex used above for removing a class can also be used as a check as to whether a particular class exists:
if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )
### Assigning these actions to onClick events:
Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as onClick="this.className+=' MyClass'") this is not recommended behavior. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.
The first step to achieving this is by creating a function, and calling the function in the onClick attribute, for example:
<script type="text/javascript">
function changeClass(){
// Code examples from above
}
</script>
...
<button onClick="changeClass()">My Button</button>
(It is not required to have this code in script tags, this is simply for the brevity of example, and including the JavaScript in a distinct file may be more appropriate.)
The second step is to move the onClick event out of the HTML and into JavaScript, for example using addEventListener
<script type="text/javascript">
function changeClass(){
// Code examples from above
}
window.onload = function(){
document.getElementById("MyElement").addEventListener( 'click', changeClass);
}
</script>
...
<button id="MyElement">My Button</button>
(Note that the window.onload part is required so that the contents of that function are executed after the HTML has finished loading - without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)
JavaScript Frameworks and Libraries
The above code is all in standard JavaScript, however, it is common practice to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.
Whilst some people consider it overkill to add a ~50  KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work or anything that might have unusual cross-browser behavior, it is well worth considering.
(Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.)
The examples above have been reproduced below using jQuery, probably the most commonly used JavaScript library (though there are others worth investigating too).
(Note that $ here is the jQuery object.)
Changing Classes with jQuery:
$('#MyElement').addClass('MyClass');
$('#MyElement').removeClass('MyClass');
if ( $('#MyElement').hasClass('MyClass') )
In addition, jQuery provides a shortcut for adding a class if it doesn't apply, or removing a class that does:
$('#MyElement').toggleClass('MyClass');
### Assigning a function to a click event with jQuery:
$('#MyElement').click(changeClass);
or, without needing an id:
$(':button:contains(My Button)').click(changeClass);
You could also just do:
document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');
And to toggle a class (remove if exists else add it):
document.getElementById('id').classList.toggle('class');
In one of my old projects that did not use jQuery, I built the following functions for adding, removing and checking if an element has a class:
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(ele, cls) {
if (!hasClass(ele, cls))
ele.className += " " + cls;
}
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ');
}
}
So, for example, if I want onclick to add some class to the button I can use this:
<script type="text/javascript">
function changeClass(btn, cls) {
if(!hasClass(btn, cls)) {
addClass(btn, cls);
}
}
</script>
...
<button onclick="changeClass(this, "someClass")">My Button</button>
By now for sure it would just be better to use jQuery.
You can use node.className like so:
document.getElementById('foo').className = 'bar';
This should work in Internet Explorer 5.5 and up according to PPK.
Wow, surprised there are so many overkill answers here...
<div class="firstClass" onclick="this.className='secondClass'">
Using pure JavaScript code:
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(ele, cls) {
if (!this.hasClass(ele, cls)) ele.className += " " + cls;
}
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ');
}
}
function replaceClass(ele, oldClass, newClass){
if(hasClass(ele, oldClass)){
removeClass(ele, oldClass);
addClass(ele, newClass);
}
return;
}
function toggleClass(ele, cls1, cls2){
if(hasClass(ele, cls1)){
replaceClass(ele, cls1, cls2);
}else if(hasClass(ele, cls2)){
replaceClass(ele, cls2, cls1);
}else{
addClass(ele, cls1);
}
}
4 actions possible: Add, Remove, Check, and Toggle
Let's see multiple ways for each action.
1. Add class
Method 1: Best way to add a class in the modern browser is using classList.add() method of element.
Case 1: Adding single class
function addClass() {
let element = document.getElementById('id1');
// adding class
element.classList.add('beautify');
}
Case 2: Adding multiple class
To add multiple classes saperate classes by a comma in the add() method
function addClass() {
let element = document.getElementById('id1');
// adding multiple class
element.classList.add('class1', 'class2', 'class3');
}
Method 2 - You can also add classes to HTML elements using className property.
Case 1: Overwriting pre-existing classes
When you assign a new class to the className property it overwrites the previous class.
function addClass() {
let element = document.getElementById('id1');
// adding multiple class
element.className = 'beautify';
}
Case 2: Adding class without overwrite
Use += operator for class not to overwrite previous classes. Also, add an extra space before the new class.
function addClass() {
let element = document.getElementById('id1');
// adding single multiple class
element.className += ' beautify';
// adding multiple classes
element.className += ' class1 class2 class3';
}
2. Remove class
Method 1 - The best way to remove a class from an element is the classList.remove() method.
Case 1: Remove single class
Just pass the class name you want to remove from the element in the method.
function removeClass() {
let element = document.getElementById('id1');
// removing class
element.classList.remove('beautify');
}
Case 2: Remove multiple class
Pass multiple classes separated by a comma.
function removeClass() {
let element = document.getElementById('id1');
// removing class
element.classList.remove('class1', 'class2', 'class3');
}
Method 2 - You can also remove class using className method.
Case 1: Removing single class
If the element has only 1 class and you want to remove it then just assign an empty string to the className method.
function removeClass() {
let element = document.getElementById('id1');
// removing class
element.className = '';
}
Case 2: Removing multiple class
If the element has multiple classes first get all classes from the element using the className property and use replace method and replace desired classes with an empty string and finally assign it to element's className property.
function removeClass() {
let element = document.getElementById('id1');
// removing class
element.className = element.className.replace('class1', '');
}
3. Checking class
To check if a class exists in the element you can simply use classList.contains() method. It returns true if the class exists else returns false.
function checkClass() {
let element = document.getElementById('id1');
// checking class
if(element.classList.contains('beautify') {
alert('Yes! class exists');
}
}
4. Toggle class
To toggle a class use classList.toggle() method.
function toggleClass() {
let element = document.getElementById('id1');
// toggle class
element.classList.toggle('beautify');
}
This is working for me:
function setCSS(eleID) {
var currTabElem = document.getElementById(eleID);
currTabElem.setAttribute("class", "some_class_name");
currTabElem.setAttribute("className", "some_class_name");
}
As well you could extend HTMLElement object, in order to add methods to add, remove, toggle and check classes (gist):
HTMLElement = typeof(HTMLElement) != 'undefiend' ? HTMLElement : Element;
HTMLElement.prototype.addClass = function(string) {
if (!(string instanceof Array)) {
string = string.split(' ');
}
for(var i = 0, len = string.length; i < len; ++i) {
if (string[i] && !new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)').test(this.className)) {
this.className = this.className.trim() + ' ' + string[i];
}
}
}
HTMLElement.prototype.removeClass = function(string) {
if (!(string instanceof Array)) {
string = string.split(' ');
}
for(var i = 0, len = string.length; i < len; ++i) {
this.className = this.className.replace(new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)'), ' ').trim();
}
}
HTMLElement.prototype.toggleClass = function(string) {
if (string) {
if (new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className)) {
this.className = this.className.replace(new RegExp('(\\s+|^)' + string + '(\\s+|$)'), ' ').trim();
} else {
this.className = this.className.trim() + ' ' + string;
}
}
}
HTMLElement.prototype.hasClass = function(string) {
return string && new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className);
}
And then just use like this (on click will add or remove class):
document.getElementById('yourElementId').onclick = function() {
this.toggleClass('active');
}
Here is demo.
Just to add on information from another popular framework, Google Closures, see their dom/classes class:
goog.dom.classes.add(element, var_args)
goog.dom.classes.addRemove(element, classesToRemove, classesToAdd)
goog.dom.classes.remove(element, var_args)
One option for selecting the element is using goog.dom.query with a CSS 3 selector:
var myElement = goog.dom.query("#MyElement")[0];
A couple of minor notes and tweaks on the previous regexes:
You'll want to do it globally in case the class list has the class name more than once. And, you'll probably want to strip spaces from the ends of the class list and convert multiple spaces to one space to keep from getting runs of spaces. None of these things should be a problem if the only code dinking with the class names uses the regex below and removes a name before adding it. But. Well, who knows who might be dinking with the class name list.
This regex is case insensitive so that bugs in class names may show up before the code is used on a browser that doesn't care about case in class names.
var s = "testing one four one two";
var cls = "one";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "test";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "testing";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "tWo";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
Change an element's CSS class with JavaScript in ASP.NET:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
lbSave.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")
lbSave.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")
lbCancel.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")
lbCancel.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")
End If
End Sub
I would use jQuery and write something like this:
jQuery(function($) {
$("#some-element").click(function() {
$(this).toggleClass("clicked");
});
});
This code adds a function to be called when an element of the id some-element is clicked. The function appends clicked to the element's class attribute if it's not already part of it, and removes it if it's there.
Yes, you do need to add a reference to the jQuery library in your page to use this code, but at least you can feel confident the most functions in the library would work on pretty much all the modern browsers, and it will save you time implementing your own code to do the same.
The line
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/\bMyClass\b/','')
should be:
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace('/\bMyClass\b/','');
Change an element's class in vanilla JavaScript with Internet Explorer 6 support
You may try to use the node attributes property to keep compatibility with old browsers, even Internet Explorer 6:
function getClassNode(element) {
for (var i = element.attributes.length; i--;)
if (element.attributes[i].nodeName === 'class')
return element.attributes[i];
}
function removeClass(classNode, className) {
var index, classList = classNode.value.split(' ');
if ((index = classList.indexOf(className)) > -1) {
classList.splice(index, 1);
classNode.value = classList.join(' ');
}
}
function hasClass(classNode, className) {
return classNode.value.indexOf(className) > -1;
}
function addClass(classNode, className) {
if (!hasClass(classNode, className))
classNode.value += ' ' + className;
}
document.getElementById('message').addEventListener('click', function() {
var classNode = getClassNode(this);
var className = hasClass(classNode, 'red') && 'blue' || 'red';
removeClass(classNode, 'red');
removeClass(classNode, 'blue');
addClass(classNode, className);
})
.red {
color: red;
}
.red:before {
content: 'I am red! ';
}
.red:after {
content: ' again';
}
.blue {
color: blue;
}
.blue:before {
content: 'I am blue! '
}
<span id="message" class="">Click me</span>
Here's my version, fully working:
function addHTMLClass(item, classname) {
var obj = item
if (typeof item=="string") {
obj = document.getElementById(item)
}
obj.className += " " + classname
}
function removeHTMLClass(item, classname) {
var obj = item
if (typeof item=="string") {
obj = document.getElementById(item)
}
var classes = ""+obj.className
while (classes.indexOf(classname)>-1) {
classes = classes.replace (classname, "")
}
obj.className = classes
}
Usage:
<tr onmouseover='addHTMLClass(this,"clsSelected")'
onmouseout='removeHTMLClass(this,"clsSelected")' >
Here's a toggleClass to toggle/add/remove a class on an element:
// If newState is provided add/remove theClass accordingly, otherwise toggle theClass
function toggleClass(elem, theClass, newState) {
var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');
var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null));
elem.className=elem.className.replace(matchRegExp, ''); // clear all
if (add) elem.className += ' ' + theClass;
}
See the JSFiddle.
Also see my answer here for creating a new class dynamically.
I use the following vanilla JavaScript functions in my code. They use regular expressions and indexOf but do not require quoting special characters in regular expressions.
function addClass(el, cn) {
var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
c1 = (" " + cn + " ").replace(/\s+/g, " ");
if (c0.indexOf(c1) < 0) {
el.className = (c0 + c1).replace(/\s+/g, " ").replace(/^ | $/g, "");
}
}
function delClass(el, cn) {
var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
c1 = (" " + cn + " ").replace(/\s+/g, " ");
if (c0.indexOf(c1) >= 0) {
el.className = c0.replace(c1, " ").replace(/\s+/g, " ").replace(/^ | $/g, "");
}
}
You can also use element.classList in modern browsers.
The OP question was How can I change an element's class with JavaScript?
Modern browsers allow you to do this with one line of JavaScript:
document.getElementById('id').classList.replace('span1', 'span2')
The classList attribute provides a DOMTokenList which has a variety of methods. You can operate on an element's classList using simple manipulations like add(), remove() or replace(). Or get very sophisticated and manipulate classes like you would an object or Map with keys(), values(), and entries().
Peter Boughton's answer is a great one, but it's now over a decade old. All modern browsers now support DOMTokenList - see https://caniuse.com/#search=classList and even Internet Explorer 11 supports some DOMTokenList methods.
THE OPTIONS.
Here is a little style vs. classList examples to get you to see what are the options you have available and how to use classList to do what you want.
style vs. classList
The difference between style and classList is that with style you're adding to the style properties of the element, but classList is kinda controlling the class(es) of the element (add, remove, toggle, contain), I will show you how to use the add and remove method since those are the popular ones.
Style Example
If you want to add margin-top property into an element, you would do in such:
// Get the Element
const el = document.querySelector('#element');
// Add CSS property
el.style.margintop = "0px"
el.style.margintop = "25px" // This would add a 25px to the top of the element.
classList Example
Let say we have a <div class="class-a class-b">, in this case, we have 2 classes added to our div element already, class-a and class-b, and we want to control what classes remove and what class to add. This is where classList becomes handy.
Remove class-b
// Get the Element
const el = document.querySelector('#element');
// Remove class-b style from the element
el.classList.remove("class-b")
Add class-c
// Get the Element
const el = document.querySelector('#element');
// Add class-b style from the element
el.classList.add("class-c")
Try:
element.className='second'
function change(box) { box.className='second' }
.first { width: 70px; height: 70px; background: #ff0 }
.second { width: 150px; height: 150px; background: #f00; transition: 1s }
<div onclick="change(this)" class="first">Click me</div>
For IE v6-9 (in which classList is not supported and you don't want to use polyfills):
var elem = document.getElementById('some-id');
// don't forget the extra space before the class name
var classList = elem.getAttribute('class') + ' other-class-name';
elem.setAttribute('class', classList);
OK, I think in this case you should use jQuery or write your own Methods in pure JavaScript. My preference is adding my own methods rather than injecting all jQuery to my application if I don't need that for other reasons.
I'd like to do something like below as methods to my JavaScript framework to add few functionalities which handle adding classes, deleting classes, etc. Similar to jQuery, this is fully supported in IE9+. Also my code is written in ES6, so you need to make sure your browser support it or you using something like Babel, otherwise need to use ES5 syntax in your code. Also in this way, we finding element via ID, which means the element needs to have an ID to be selected:
// Simple JavaScript utilities for class management in ES6
var classUtil = {
addClass: (id, cl) => {
document.getElementById(id).classList.add(cl);
},
removeClass: (id, cl) => {
document.getElementById(id).classList.remove(cl);
},
hasClass: (id, cl) => {
return document.getElementById(id).classList.contains(cl);
},
toggleClass: (id, cl) => {
document.getElementById(id).classList.toggle(cl);
}
}
And you can simply use them as below. Imagine your element has id of 'id' and class of 'class'. Make sure you pass them as a string. You can use the utility as below:
classUtil.addClass('myId', 'myClass');
classUtil.removeClass('myId', 'myClass');
classUtil.hasClass('myId', 'myClass');
classUtil.toggleClass('myId', 'myClass');
classList DOM API:
A very convenient manner of adding and removing classes is the classList DOM API. This API allows us to select all classes of a specific DOM element in order to modify the list using JavaScript. For example:
const el = document.getElementById("main");
console.log(el.classList);
<div class="content wrapper animated" id="main"></div>
We can observe in the log that we are getting back an object with not only the classes of the element, but also many auxiliary methods and properties. This object inherits from the interface DOMTokenList, an interface which is used in the DOM to represent a set of space separated tokens (like classes).
Example:
const el = document.getElementById('container');
function addClass () {
el.classList.add('newclass');
}
function replaceClass () {
el.classList.replace('foo', 'newFoo');
}
function removeClass () {
el.classList.remove('bar');
}
button{
margin: 20px;
}
.foo{
color: red;
}
.newFoo {
color: blue;
}
.bar{
background-color: powderblue;
}
.newclass{
border: 2px solid green;
}
<div class="foo bar" id="container">
"Sed ut perspiciatis unde omnis
iste natus error sit voluptatem accusantium doloremque laudantium,
totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et
quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam
voluptatem quia voluptas
</div>
<button onclick="addClass()">AddClass</button>
<button onclick="replaceClass()">ReplaceClass</button>
<button onclick="removeClass()">removeClass</button>
Yes, there are many ways to do this. In ES6 syntax we can achieve easily. Use this code toggle add and remove class.
const tabs=document.querySelectorAll('.menu li');
for(let tab of tabs){
tab.onclick = function(){
let activetab = document.querySelectorAll('li.active');
activetab[0].classList.remove('active')
tab.classList.add('active');
}
}
body {
padding: 20px;
font-family: sans-serif;
}
ul {
margin: 20px 0;
list-style: none;
}
li {
background: #dfdfdf;
padding: 10px;
margin: 6px 0;
cursor: pointer;
}
li.active {
background: #2794c7;
font-weight: bold;
color: #ffffff;
}
<i>Please click an item:</i>
<ul class="menu">
<li class="active"><span>Three</span></li>
<li><span>Two</span></li>
<li><span>One</span></li>
</ul>
Just thought I'd throw this in:
function inArray(val, ary){
for(var i=0,l=ary.length; i<l; i++){
if(ary[i] === val){
return true;
}
}
return false;
}
function removeClassName(classNameS, fromElement){
var x = classNameS.split(/\s/), s = fromElement.className.split(/\s/), r = [];
for(var i=0,l=s.length; i<l; i++){
if(!iA(s[i], x))r.push(s[i]);
}
fromElement.className = r.join(' ');
}
function addClassName(classNameS, toElement){
var s = toElement.className.split(/\s/);
s.push(c); toElement.className = s.join(' ');
}
Just use myElement.classList="new-class" unless you need to maintain other existing classes in which case you can use the classList.add, .remove methods.
var doc = document;
var divOne = doc.getElementById("one");
var goButton = doc.getElementById("go");
goButton.addEventListener("click", function() {
divOne.classList="blue";
});
div{
min-height: 48px;
min-width: 48px;
}
.bordered{
border: 1px solid black;
}
.green{
background: green;
}
.blue{
background: blue;
}
<button id="go">Change Class</button>
<div id="one" class="bordered green">
</div>
TL;DR:
document.getElementById('id').className = 'class'
OR
document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');
That's it.
And, if you really want to know the why and educate yourself then I suggest reading Peter Boughton's answer. It's perfect.
Note:
This is possible with (document or event):
getElementById()
getElementsByClassName()
querySelector()
querySelectorAll()
function classed(el, class_name, add_class) {
const re = new RegExp("(?:^|\\s)" + class_name + "(?!\\S)", "g");
if (add_class && !el.className.match(re)) el.className += " " + class_name
else if (!add_class) el.className = el.className.replace(re, '');
}
Using Peter Boughton's answer, here is a simple cross-browser function to add and remove class.
Add class:
classed(document.getElementById("denis"), "active", true)
Remove class:
classed(document.getElementById("denis"), "active", false)
There is a property, className, in JavaScript to change the name of the class of an HTML element. The existing class value will be replaced with the new one, that you have assigned in className.
<!DOCTYPE html>
<html>
<head>
<title>How can I change the class of an HTML element in JavaScript?</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<h1 align="center"><i class="fa fa-home" id="icon"></i></h1><br />
<center><button id="change-class">Change Class</button></center>
<script>
var change_class = document.getElementById("change-class");
change_class.onclick = function()
{
var icon=document.getElementById("icon");
icon.className = "fa fa-gear";
}
</script>
</body>
</html>
Credit - How To Change Class Name of an HTML Element in JavaScript

How to change elements class with JavaScript? [duplicate]

How can I change the class of an HTML element in response to an onclick or any other events using JavaScript?
Modern HTML5 Techniques for changing classes
Modern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library:
document.getElementById("MyElement").classList.add('MyClass');
document.getElementById("MyElement").classList.remove('MyClass');
if ( document.getElementById("MyElement").classList.contains('MyClass') )
document.getElementById("MyElement").classList.toggle('MyClass');
Unfortunately, these do not work in Internet Explorer prior to v10, though there is a shim to add support for it to IE8 and IE9, available from this page. It is, though, getting more and more supported.
Simple cross-browser solution
The standard JavaScript way to select an element is using document.getElementById("Id"), which is what the following examples use - you can of course obtain elements in other ways, and in the right situation may simply use this instead - however, going into detail on this is beyond the scope of the answer.
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.)
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 remove a class from an element:
To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:
document.getElementById("MyElement").className =
document.getElementById("MyElement").className.replace
( /(?:^|\s)MyClass(?!\S)/g , '' )
/* Code wrapped for readability - above is all one statement */
An explanation of this regex is as follows:
(?:^|\s) # Match the start of the string or any single whitespace character
MyClass # The literal text for the classname to remove
(?!\S) # Negative lookahead to verify the above is the whole classname
# Ensures there is no non-space character following
# (i.e. must be the end of the string or space)
The g flag tells the replace to repeat as required, in case the class name has been added multiple times.
To check if a class is already applied to an element:
The same regex used above for removing a class can also be used as a check as to whether a particular class exists:
if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )
### Assigning these actions to onClick events:
Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as onClick="this.className+=' MyClass'") this is not recommended behavior. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.
The first step to achieving this is by creating a function, and calling the function in the onClick attribute, for example:
<script type="text/javascript">
function changeClass(){
// Code examples from above
}
</script>
...
<button onClick="changeClass()">My Button</button>
(It is not required to have this code in script tags, this is simply for the brevity of example, and including the JavaScript in a distinct file may be more appropriate.)
The second step is to move the onClick event out of the HTML and into JavaScript, for example using addEventListener
<script type="text/javascript">
function changeClass(){
// Code examples from above
}
window.onload = function(){
document.getElementById("MyElement").addEventListener( 'click', changeClass);
}
</script>
...
<button id="MyElement">My Button</button>
(Note that the window.onload part is required so that the contents of that function are executed after the HTML has finished loading - without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)
JavaScript Frameworks and Libraries
The above code is all in standard JavaScript, however, it is common practice to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.
Whilst some people consider it overkill to add a ~50  KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work or anything that might have unusual cross-browser behavior, it is well worth considering.
(Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.)
The examples above have been reproduced below using jQuery, probably the most commonly used JavaScript library (though there are others worth investigating too).
(Note that $ here is the jQuery object.)
Changing Classes with jQuery:
$('#MyElement').addClass('MyClass');
$('#MyElement').removeClass('MyClass');
if ( $('#MyElement').hasClass('MyClass') )
In addition, jQuery provides a shortcut for adding a class if it doesn't apply, or removing a class that does:
$('#MyElement').toggleClass('MyClass');
### Assigning a function to a click event with jQuery:
$('#MyElement').click(changeClass);
or, without needing an id:
$(':button:contains(My Button)').click(changeClass);
You could also just do:
document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');
And to toggle a class (remove if exists else add it):
document.getElementById('id').classList.toggle('class');
In one of my old projects that did not use jQuery, I built the following functions for adding, removing and checking if an element has a class:
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(ele, cls) {
if (!hasClass(ele, cls))
ele.className += " " + cls;
}
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ');
}
}
So, for example, if I want onclick to add some class to the button I can use this:
<script type="text/javascript">
function changeClass(btn, cls) {
if(!hasClass(btn, cls)) {
addClass(btn, cls);
}
}
</script>
...
<button onclick="changeClass(this, "someClass")">My Button</button>
By now for sure it would just be better to use jQuery.
You can use node.className like so:
document.getElementById('foo').className = 'bar';
This should work in Internet Explorer 5.5 and up according to PPK.
Wow, surprised there are so many overkill answers here...
<div class="firstClass" onclick="this.className='secondClass'">
Using pure JavaScript code:
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(ele, cls) {
if (!this.hasClass(ele, cls)) ele.className += " " + cls;
}
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ');
}
}
function replaceClass(ele, oldClass, newClass){
if(hasClass(ele, oldClass)){
removeClass(ele, oldClass);
addClass(ele, newClass);
}
return;
}
function toggleClass(ele, cls1, cls2){
if(hasClass(ele, cls1)){
replaceClass(ele, cls1, cls2);
}else if(hasClass(ele, cls2)){
replaceClass(ele, cls2, cls1);
}else{
addClass(ele, cls1);
}
}
4 actions possible: Add, Remove, Check, and Toggle
Let's see multiple ways for each action.
1. Add class
Method 1: Best way to add a class in the modern browser is using classList.add() method of element.
Case 1: Adding single class
function addClass() {
let element = document.getElementById('id1');
// adding class
element.classList.add('beautify');
}
Case 2: Adding multiple class
To add multiple classes saperate classes by a comma in the add() method
function addClass() {
let element = document.getElementById('id1');
// adding multiple class
element.classList.add('class1', 'class2', 'class3');
}
Method 2 - You can also add classes to HTML elements using className property.
Case 1: Overwriting pre-existing classes
When you assign a new class to the className property it overwrites the previous class.
function addClass() {
let element = document.getElementById('id1');
// adding multiple class
element.className = 'beautify';
}
Case 2: Adding class without overwrite
Use += operator for class not to overwrite previous classes. Also, add an extra space before the new class.
function addClass() {
let element = document.getElementById('id1');
// adding single multiple class
element.className += ' beautify';
// adding multiple classes
element.className += ' class1 class2 class3';
}
2. Remove class
Method 1 - The best way to remove a class from an element is the classList.remove() method.
Case 1: Remove single class
Just pass the class name you want to remove from the element in the method.
function removeClass() {
let element = document.getElementById('id1');
// removing class
element.classList.remove('beautify');
}
Case 2: Remove multiple class
Pass multiple classes separated by a comma.
function removeClass() {
let element = document.getElementById('id1');
// removing class
element.classList.remove('class1', 'class2', 'class3');
}
Method 2 - You can also remove class using className method.
Case 1: Removing single class
If the element has only 1 class and you want to remove it then just assign an empty string to the className method.
function removeClass() {
let element = document.getElementById('id1');
// removing class
element.className = '';
}
Case 2: Removing multiple class
If the element has multiple classes first get all classes from the element using the className property and use replace method and replace desired classes with an empty string and finally assign it to element's className property.
function removeClass() {
let element = document.getElementById('id1');
// removing class
element.className = element.className.replace('class1', '');
}
3. Checking class
To check if a class exists in the element you can simply use classList.contains() method. It returns true if the class exists else returns false.
function checkClass() {
let element = document.getElementById('id1');
// checking class
if(element.classList.contains('beautify') {
alert('Yes! class exists');
}
}
4. Toggle class
To toggle a class use classList.toggle() method.
function toggleClass() {
let element = document.getElementById('id1');
// toggle class
element.classList.toggle('beautify');
}
This is working for me:
function setCSS(eleID) {
var currTabElem = document.getElementById(eleID);
currTabElem.setAttribute("class", "some_class_name");
currTabElem.setAttribute("className", "some_class_name");
}
As well you could extend HTMLElement object, in order to add methods to add, remove, toggle and check classes (gist):
HTMLElement = typeof(HTMLElement) != 'undefiend' ? HTMLElement : Element;
HTMLElement.prototype.addClass = function(string) {
if (!(string instanceof Array)) {
string = string.split(' ');
}
for(var i = 0, len = string.length; i < len; ++i) {
if (string[i] && !new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)').test(this.className)) {
this.className = this.className.trim() + ' ' + string[i];
}
}
}
HTMLElement.prototype.removeClass = function(string) {
if (!(string instanceof Array)) {
string = string.split(' ');
}
for(var i = 0, len = string.length; i < len; ++i) {
this.className = this.className.replace(new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)'), ' ').trim();
}
}
HTMLElement.prototype.toggleClass = function(string) {
if (string) {
if (new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className)) {
this.className = this.className.replace(new RegExp('(\\s+|^)' + string + '(\\s+|$)'), ' ').trim();
} else {
this.className = this.className.trim() + ' ' + string;
}
}
}
HTMLElement.prototype.hasClass = function(string) {
return string && new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className);
}
And then just use like this (on click will add or remove class):
document.getElementById('yourElementId').onclick = function() {
this.toggleClass('active');
}
Here is demo.
Just to add on information from another popular framework, Google Closures, see their dom/classes class:
goog.dom.classes.add(element, var_args)
goog.dom.classes.addRemove(element, classesToRemove, classesToAdd)
goog.dom.classes.remove(element, var_args)
One option for selecting the element is using goog.dom.query with a CSS 3 selector:
var myElement = goog.dom.query("#MyElement")[0];
A couple of minor notes and tweaks on the previous regexes:
You'll want to do it globally in case the class list has the class name more than once. And, you'll probably want to strip spaces from the ends of the class list and convert multiple spaces to one space to keep from getting runs of spaces. None of these things should be a problem if the only code dinking with the class names uses the regex below and removes a name before adding it. But. Well, who knows who might be dinking with the class name list.
This regex is case insensitive so that bugs in class names may show up before the code is used on a browser that doesn't care about case in class names.
var s = "testing one four one two";
var cls = "one";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "test";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "testing";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "tWo";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
Change an element's CSS class with JavaScript in ASP.NET:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
lbSave.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")
lbSave.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")
lbCancel.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")
lbCancel.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")
End If
End Sub
I would use jQuery and write something like this:
jQuery(function($) {
$("#some-element").click(function() {
$(this).toggleClass("clicked");
});
});
This code adds a function to be called when an element of the id some-element is clicked. The function appends clicked to the element's class attribute if it's not already part of it, and removes it if it's there.
Yes, you do need to add a reference to the jQuery library in your page to use this code, but at least you can feel confident the most functions in the library would work on pretty much all the modern browsers, and it will save you time implementing your own code to do the same.
The line
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/\bMyClass\b/','')
should be:
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace('/\bMyClass\b/','');
Change an element's class in vanilla JavaScript with Internet Explorer 6 support
You may try to use the node attributes property to keep compatibility with old browsers, even Internet Explorer 6:
function getClassNode(element) {
for (var i = element.attributes.length; i--;)
if (element.attributes[i].nodeName === 'class')
return element.attributes[i];
}
function removeClass(classNode, className) {
var index, classList = classNode.value.split(' ');
if ((index = classList.indexOf(className)) > -1) {
classList.splice(index, 1);
classNode.value = classList.join(' ');
}
}
function hasClass(classNode, className) {
return classNode.value.indexOf(className) > -1;
}
function addClass(classNode, className) {
if (!hasClass(classNode, className))
classNode.value += ' ' + className;
}
document.getElementById('message').addEventListener('click', function() {
var classNode = getClassNode(this);
var className = hasClass(classNode, 'red') && 'blue' || 'red';
removeClass(classNode, 'red');
removeClass(classNode, 'blue');
addClass(classNode, className);
})
.red {
color: red;
}
.red:before {
content: 'I am red! ';
}
.red:after {
content: ' again';
}
.blue {
color: blue;
}
.blue:before {
content: 'I am blue! '
}
<span id="message" class="">Click me</span>
Here's my version, fully working:
function addHTMLClass(item, classname) {
var obj = item
if (typeof item=="string") {
obj = document.getElementById(item)
}
obj.className += " " + classname
}
function removeHTMLClass(item, classname) {
var obj = item
if (typeof item=="string") {
obj = document.getElementById(item)
}
var classes = ""+obj.className
while (classes.indexOf(classname)>-1) {
classes = classes.replace (classname, "")
}
obj.className = classes
}
Usage:
<tr onmouseover='addHTMLClass(this,"clsSelected")'
onmouseout='removeHTMLClass(this,"clsSelected")' >
Here's a toggleClass to toggle/add/remove a class on an element:
// If newState is provided add/remove theClass accordingly, otherwise toggle theClass
function toggleClass(elem, theClass, newState) {
var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');
var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null));
elem.className=elem.className.replace(matchRegExp, ''); // clear all
if (add) elem.className += ' ' + theClass;
}
See the JSFiddle.
Also see my answer here for creating a new class dynamically.
I use the following vanilla JavaScript functions in my code. They use regular expressions and indexOf but do not require quoting special characters in regular expressions.
function addClass(el, cn) {
var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
c1 = (" " + cn + " ").replace(/\s+/g, " ");
if (c0.indexOf(c1) < 0) {
el.className = (c0 + c1).replace(/\s+/g, " ").replace(/^ | $/g, "");
}
}
function delClass(el, cn) {
var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
c1 = (" " + cn + " ").replace(/\s+/g, " ");
if (c0.indexOf(c1) >= 0) {
el.className = c0.replace(c1, " ").replace(/\s+/g, " ").replace(/^ | $/g, "");
}
}
You can also use element.classList in modern browsers.
The OP question was How can I change an element's class with JavaScript?
Modern browsers allow you to do this with one line of JavaScript:
document.getElementById('id').classList.replace('span1', 'span2')
The classList attribute provides a DOMTokenList which has a variety of methods. You can operate on an element's classList using simple manipulations like add(), remove() or replace(). Or get very sophisticated and manipulate classes like you would an object or Map with keys(), values(), and entries().
Peter Boughton's answer is a great one, but it's now over a decade old. All modern browsers now support DOMTokenList - see https://caniuse.com/#search=classList and even Internet Explorer 11 supports some DOMTokenList methods.
THE OPTIONS.
Here is a little style vs. classList examples to get you to see what are the options you have available and how to use classList to do what you want.
style vs. classList
The difference between style and classList is that with style you're adding to the style properties of the element, but classList is kinda controlling the class(es) of the element (add, remove, toggle, contain), I will show you how to use the add and remove method since those are the popular ones.
Style Example
If you want to add margin-top property into an element, you would do in such:
// Get the Element
const el = document.querySelector('#element');
// Add CSS property
el.style.margintop = "0px"
el.style.margintop = "25px" // This would add a 25px to the top of the element.
classList Example
Let say we have a <div class="class-a class-b">, in this case, we have 2 classes added to our div element already, class-a and class-b, and we want to control what classes remove and what class to add. This is where classList becomes handy.
Remove class-b
// Get the Element
const el = document.querySelector('#element');
// Remove class-b style from the element
el.classList.remove("class-b")
Add class-c
// Get the Element
const el = document.querySelector('#element');
// Add class-b style from the element
el.classList.add("class-c")
Try:
element.className='second'
function change(box) { box.className='second' }
.first { width: 70px; height: 70px; background: #ff0 }
.second { width: 150px; height: 150px; background: #f00; transition: 1s }
<div onclick="change(this)" class="first">Click me</div>
For IE v6-9 (in which classList is not supported and you don't want to use polyfills):
var elem = document.getElementById('some-id');
// don't forget the extra space before the class name
var classList = elem.getAttribute('class') + ' other-class-name';
elem.setAttribute('class', classList);
OK, I think in this case you should use jQuery or write your own Methods in pure JavaScript. My preference is adding my own methods rather than injecting all jQuery to my application if I don't need that for other reasons.
I'd like to do something like below as methods to my JavaScript framework to add few functionalities which handle adding classes, deleting classes, etc. Similar to jQuery, this is fully supported in IE9+. Also my code is written in ES6, so you need to make sure your browser support it or you using something like Babel, otherwise need to use ES5 syntax in your code. Also in this way, we finding element via ID, which means the element needs to have an ID to be selected:
// Simple JavaScript utilities for class management in ES6
var classUtil = {
addClass: (id, cl) => {
document.getElementById(id).classList.add(cl);
},
removeClass: (id, cl) => {
document.getElementById(id).classList.remove(cl);
},
hasClass: (id, cl) => {
return document.getElementById(id).classList.contains(cl);
},
toggleClass: (id, cl) => {
document.getElementById(id).classList.toggle(cl);
}
}
And you can simply use them as below. Imagine your element has id of 'id' and class of 'class'. Make sure you pass them as a string. You can use the utility as below:
classUtil.addClass('myId', 'myClass');
classUtil.removeClass('myId', 'myClass');
classUtil.hasClass('myId', 'myClass');
classUtil.toggleClass('myId', 'myClass');
classList DOM API:
A very convenient manner of adding and removing classes is the classList DOM API. This API allows us to select all classes of a specific DOM element in order to modify the list using JavaScript. For example:
const el = document.getElementById("main");
console.log(el.classList);
<div class="content wrapper animated" id="main"></div>
We can observe in the log that we are getting back an object with not only the classes of the element, but also many auxiliary methods and properties. This object inherits from the interface DOMTokenList, an interface which is used in the DOM to represent a set of space separated tokens (like classes).
Example:
const el = document.getElementById('container');
function addClass () {
el.classList.add('newclass');
}
function replaceClass () {
el.classList.replace('foo', 'newFoo');
}
function removeClass () {
el.classList.remove('bar');
}
button{
margin: 20px;
}
.foo{
color: red;
}
.newFoo {
color: blue;
}
.bar{
background-color: powderblue;
}
.newclass{
border: 2px solid green;
}
<div class="foo bar" id="container">
"Sed ut perspiciatis unde omnis
iste natus error sit voluptatem accusantium doloremque laudantium,
totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et
quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam
voluptatem quia voluptas
</div>
<button onclick="addClass()">AddClass</button>
<button onclick="replaceClass()">ReplaceClass</button>
<button onclick="removeClass()">removeClass</button>
Yes, there are many ways to do this. In ES6 syntax we can achieve easily. Use this code toggle add and remove class.
const tabs=document.querySelectorAll('.menu li');
for(let tab of tabs){
tab.onclick = function(){
let activetab = document.querySelectorAll('li.active');
activetab[0].classList.remove('active')
tab.classList.add('active');
}
}
body {
padding: 20px;
font-family: sans-serif;
}
ul {
margin: 20px 0;
list-style: none;
}
li {
background: #dfdfdf;
padding: 10px;
margin: 6px 0;
cursor: pointer;
}
li.active {
background: #2794c7;
font-weight: bold;
color: #ffffff;
}
<i>Please click an item:</i>
<ul class="menu">
<li class="active"><span>Three</span></li>
<li><span>Two</span></li>
<li><span>One</span></li>
</ul>
Just thought I'd throw this in:
function inArray(val, ary){
for(var i=0,l=ary.length; i<l; i++){
if(ary[i] === val){
return true;
}
}
return false;
}
function removeClassName(classNameS, fromElement){
var x = classNameS.split(/\s/), s = fromElement.className.split(/\s/), r = [];
for(var i=0,l=s.length; i<l; i++){
if(!iA(s[i], x))r.push(s[i]);
}
fromElement.className = r.join(' ');
}
function addClassName(classNameS, toElement){
var s = toElement.className.split(/\s/);
s.push(c); toElement.className = s.join(' ');
}
Just use myElement.classList="new-class" unless you need to maintain other existing classes in which case you can use the classList.add, .remove methods.
var doc = document;
var divOne = doc.getElementById("one");
var goButton = doc.getElementById("go");
goButton.addEventListener("click", function() {
divOne.classList="blue";
});
div{
min-height: 48px;
min-width: 48px;
}
.bordered{
border: 1px solid black;
}
.green{
background: green;
}
.blue{
background: blue;
}
<button id="go">Change Class</button>
<div id="one" class="bordered green">
</div>
TL;DR:
document.getElementById('id').className = 'class'
OR
document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');
That's it.
And, if you really want to know the why and educate yourself then I suggest reading Peter Boughton's answer. It's perfect.
Note:
This is possible with (document or event):
getElementById()
getElementsByClassName()
querySelector()
querySelectorAll()
function classed(el, class_name, add_class) {
const re = new RegExp("(?:^|\\s)" + class_name + "(?!\\S)", "g");
if (add_class && !el.className.match(re)) el.className += " " + class_name
else if (!add_class) el.className = el.className.replace(re, '');
}
Using Peter Boughton's answer, here is a simple cross-browser function to add and remove class.
Add class:
classed(document.getElementById("denis"), "active", true)
Remove class:
classed(document.getElementById("denis"), "active", false)
There is a property, className, in JavaScript to change the name of the class of an HTML element. The existing class value will be replaced with the new one, that you have assigned in className.
<!DOCTYPE html>
<html>
<head>
<title>How can I change the class of an HTML element in JavaScript?</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<h1 align="center"><i class="fa fa-home" id="icon"></i></h1><br />
<center><button id="change-class">Change Class</button></center>
<script>
var change_class = document.getElementById("change-class");
change_class.onclick = function()
{
var icon=document.getElementById("icon");
icon.className = "fa fa-gear";
}
</script>
</body>
</html>
Credit - How To Change Class Name of an HTML Element in JavaScript

Raw JS removing of a class [duplicate]

How can I change the class of an HTML element in response to an onclick or any other events using JavaScript?
Modern HTML5 Techniques for changing classes
Modern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library:
document.getElementById("MyElement").classList.add('MyClass');
document.getElementById("MyElement").classList.remove('MyClass');
if ( document.getElementById("MyElement").classList.contains('MyClass') )
document.getElementById("MyElement").classList.toggle('MyClass');
Unfortunately, these do not work in Internet Explorer prior to v10, though there is a shim to add support for it to IE8 and IE9, available from this page. It is, though, getting more and more supported.
Simple cross-browser solution
The standard JavaScript way to select an element is using document.getElementById("Id"), which is what the following examples use - you can of course obtain elements in other ways, and in the right situation may simply use this instead - however, going into detail on this is beyond the scope of the answer.
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.)
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 remove a class from an element:
To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:
document.getElementById("MyElement").className =
document.getElementById("MyElement").className.replace
( /(?:^|\s)MyClass(?!\S)/g , '' )
/* Code wrapped for readability - above is all one statement */
An explanation of this regex is as follows:
(?:^|\s) # Match the start of the string or any single whitespace character
MyClass # The literal text for the classname to remove
(?!\S) # Negative lookahead to verify the above is the whole classname
# Ensures there is no non-space character following
# (i.e. must be the end of the string or space)
The g flag tells the replace to repeat as required, in case the class name has been added multiple times.
To check if a class is already applied to an element:
The same regex used above for removing a class can also be used as a check as to whether a particular class exists:
if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )
### Assigning these actions to onClick events:
Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as onClick="this.className+=' MyClass'") this is not recommended behavior. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.
The first step to achieving this is by creating a function, and calling the function in the onClick attribute, for example:
<script type="text/javascript">
function changeClass(){
// Code examples from above
}
</script>
...
<button onClick="changeClass()">My Button</button>
(It is not required to have this code in script tags, this is simply for the brevity of example, and including the JavaScript in a distinct file may be more appropriate.)
The second step is to move the onClick event out of the HTML and into JavaScript, for example using addEventListener
<script type="text/javascript">
function changeClass(){
// Code examples from above
}
window.onload = function(){
document.getElementById("MyElement").addEventListener( 'click', changeClass);
}
</script>
...
<button id="MyElement">My Button</button>
(Note that the window.onload part is required so that the contents of that function are executed after the HTML has finished loading - without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)
JavaScript Frameworks and Libraries
The above code is all in standard JavaScript, however, it is common practice to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.
Whilst some people consider it overkill to add a ~50  KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work or anything that might have unusual cross-browser behavior, it is well worth considering.
(Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.)
The examples above have been reproduced below using jQuery, probably the most commonly used JavaScript library (though there are others worth investigating too).
(Note that $ here is the jQuery object.)
Changing Classes with jQuery:
$('#MyElement').addClass('MyClass');
$('#MyElement').removeClass('MyClass');
if ( $('#MyElement').hasClass('MyClass') )
In addition, jQuery provides a shortcut for adding a class if it doesn't apply, or removing a class that does:
$('#MyElement').toggleClass('MyClass');
### Assigning a function to a click event with jQuery:
$('#MyElement').click(changeClass);
or, without needing an id:
$(':button:contains(My Button)').click(changeClass);
You could also just do:
document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');
And to toggle a class (remove if exists else add it):
document.getElementById('id').classList.toggle('class');
In one of my old projects that did not use jQuery, I built the following functions for adding, removing and checking if an element has a class:
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(ele, cls) {
if (!hasClass(ele, cls))
ele.className += " " + cls;
}
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ');
}
}
So, for example, if I want onclick to add some class to the button I can use this:
<script type="text/javascript">
function changeClass(btn, cls) {
if(!hasClass(btn, cls)) {
addClass(btn, cls);
}
}
</script>
...
<button onclick="changeClass(this, "someClass")">My Button</button>
By now for sure it would just be better to use jQuery.
You can use node.className like so:
document.getElementById('foo').className = 'bar';
This should work in Internet Explorer 5.5 and up according to PPK.
Wow, surprised there are so many overkill answers here...
<div class="firstClass" onclick="this.className='secondClass'">
Using pure JavaScript code:
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(ele, cls) {
if (!this.hasClass(ele, cls)) ele.className += " " + cls;
}
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ');
}
}
function replaceClass(ele, oldClass, newClass){
if(hasClass(ele, oldClass)){
removeClass(ele, oldClass);
addClass(ele, newClass);
}
return;
}
function toggleClass(ele, cls1, cls2){
if(hasClass(ele, cls1)){
replaceClass(ele, cls1, cls2);
}else if(hasClass(ele, cls2)){
replaceClass(ele, cls2, cls1);
}else{
addClass(ele, cls1);
}
}
4 actions possible: Add, Remove, Check, and Toggle
Let's see multiple ways for each action.
1. Add class
Method 1: Best way to add a class in the modern browser is using classList.add() method of element.
Case 1: Adding single class
function addClass() {
let element = document.getElementById('id1');
// adding class
element.classList.add('beautify');
}
Case 2: Adding multiple class
To add multiple classes saperate classes by a comma in the add() method
function addClass() {
let element = document.getElementById('id1');
// adding multiple class
element.classList.add('class1', 'class2', 'class3');
}
Method 2 - You can also add classes to HTML elements using className property.
Case 1: Overwriting pre-existing classes
When you assign a new class to the className property it overwrites the previous class.
function addClass() {
let element = document.getElementById('id1');
// adding multiple class
element.className = 'beautify';
}
Case 2: Adding class without overwrite
Use += operator for class not to overwrite previous classes. Also, add an extra space before the new class.
function addClass() {
let element = document.getElementById('id1');
// adding single multiple class
element.className += ' beautify';
// adding multiple classes
element.className += ' class1 class2 class3';
}
2. Remove class
Method 1 - The best way to remove a class from an element is the classList.remove() method.
Case 1: Remove single class
Just pass the class name you want to remove from the element in the method.
function removeClass() {
let element = document.getElementById('id1');
// removing class
element.classList.remove('beautify');
}
Case 2: Remove multiple class
Pass multiple classes separated by a comma.
function removeClass() {
let element = document.getElementById('id1');
// removing class
element.classList.remove('class1', 'class2', 'class3');
}
Method 2 - You can also remove class using className method.
Case 1: Removing single class
If the element has only 1 class and you want to remove it then just assign an empty string to the className method.
function removeClass() {
let element = document.getElementById('id1');
// removing class
element.className = '';
}
Case 2: Removing multiple class
If the element has multiple classes first get all classes from the element using the className property and use replace method and replace desired classes with an empty string and finally assign it to element's className property.
function removeClass() {
let element = document.getElementById('id1');
// removing class
element.className = element.className.replace('class1', '');
}
3. Checking class
To check if a class exists in the element you can simply use classList.contains() method. It returns true if the class exists else returns false.
function checkClass() {
let element = document.getElementById('id1');
// checking class
if(element.classList.contains('beautify') {
alert('Yes! class exists');
}
}
4. Toggle class
To toggle a class use classList.toggle() method.
function toggleClass() {
let element = document.getElementById('id1');
// toggle class
element.classList.toggle('beautify');
}
This is working for me:
function setCSS(eleID) {
var currTabElem = document.getElementById(eleID);
currTabElem.setAttribute("class", "some_class_name");
currTabElem.setAttribute("className", "some_class_name");
}
As well you could extend HTMLElement object, in order to add methods to add, remove, toggle and check classes (gist):
HTMLElement = typeof(HTMLElement) != 'undefiend' ? HTMLElement : Element;
HTMLElement.prototype.addClass = function(string) {
if (!(string instanceof Array)) {
string = string.split(' ');
}
for(var i = 0, len = string.length; i < len; ++i) {
if (string[i] && !new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)').test(this.className)) {
this.className = this.className.trim() + ' ' + string[i];
}
}
}
HTMLElement.prototype.removeClass = function(string) {
if (!(string instanceof Array)) {
string = string.split(' ');
}
for(var i = 0, len = string.length; i < len; ++i) {
this.className = this.className.replace(new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)'), ' ').trim();
}
}
HTMLElement.prototype.toggleClass = function(string) {
if (string) {
if (new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className)) {
this.className = this.className.replace(new RegExp('(\\s+|^)' + string + '(\\s+|$)'), ' ').trim();
} else {
this.className = this.className.trim() + ' ' + string;
}
}
}
HTMLElement.prototype.hasClass = function(string) {
return string && new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className);
}
And then just use like this (on click will add or remove class):
document.getElementById('yourElementId').onclick = function() {
this.toggleClass('active');
}
Here is demo.
Just to add on information from another popular framework, Google Closures, see their dom/classes class:
goog.dom.classes.add(element, var_args)
goog.dom.classes.addRemove(element, classesToRemove, classesToAdd)
goog.dom.classes.remove(element, var_args)
One option for selecting the element is using goog.dom.query with a CSS 3 selector:
var myElement = goog.dom.query("#MyElement")[0];
A couple of minor notes and tweaks on the previous regexes:
You'll want to do it globally in case the class list has the class name more than once. And, you'll probably want to strip spaces from the ends of the class list and convert multiple spaces to one space to keep from getting runs of spaces. None of these things should be a problem if the only code dinking with the class names uses the regex below and removes a name before adding it. But. Well, who knows who might be dinking with the class name list.
This regex is case insensitive so that bugs in class names may show up before the code is used on a browser that doesn't care about case in class names.
var s = "testing one four one two";
var cls = "one";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "test";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "testing";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "tWo";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
Change an element's CSS class with JavaScript in ASP.NET:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
lbSave.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")
lbSave.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")
lbCancel.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")
lbCancel.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")
End If
End Sub
I would use jQuery and write something like this:
jQuery(function($) {
$("#some-element").click(function() {
$(this).toggleClass("clicked");
});
});
This code adds a function to be called when an element of the id some-element is clicked. The function appends clicked to the element's class attribute if it's not already part of it, and removes it if it's there.
Yes, you do need to add a reference to the jQuery library in your page to use this code, but at least you can feel confident the most functions in the library would work on pretty much all the modern browsers, and it will save you time implementing your own code to do the same.
The line
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/\bMyClass\b/','')
should be:
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace('/\bMyClass\b/','');
Change an element's class in vanilla JavaScript with Internet Explorer 6 support
You may try to use the node attributes property to keep compatibility with old browsers, even Internet Explorer 6:
function getClassNode(element) {
for (var i = element.attributes.length; i--;)
if (element.attributes[i].nodeName === 'class')
return element.attributes[i];
}
function removeClass(classNode, className) {
var index, classList = classNode.value.split(' ');
if ((index = classList.indexOf(className)) > -1) {
classList.splice(index, 1);
classNode.value = classList.join(' ');
}
}
function hasClass(classNode, className) {
return classNode.value.indexOf(className) > -1;
}
function addClass(classNode, className) {
if (!hasClass(classNode, className))
classNode.value += ' ' + className;
}
document.getElementById('message').addEventListener('click', function() {
var classNode = getClassNode(this);
var className = hasClass(classNode, 'red') && 'blue' || 'red';
removeClass(classNode, 'red');
removeClass(classNode, 'blue');
addClass(classNode, className);
})
.red {
color: red;
}
.red:before {
content: 'I am red! ';
}
.red:after {
content: ' again';
}
.blue {
color: blue;
}
.blue:before {
content: 'I am blue! '
}
<span id="message" class="">Click me</span>
Here's my version, fully working:
function addHTMLClass(item, classname) {
var obj = item
if (typeof item=="string") {
obj = document.getElementById(item)
}
obj.className += " " + classname
}
function removeHTMLClass(item, classname) {
var obj = item
if (typeof item=="string") {
obj = document.getElementById(item)
}
var classes = ""+obj.className
while (classes.indexOf(classname)>-1) {
classes = classes.replace (classname, "")
}
obj.className = classes
}
Usage:
<tr onmouseover='addHTMLClass(this,"clsSelected")'
onmouseout='removeHTMLClass(this,"clsSelected")' >
Here's a toggleClass to toggle/add/remove a class on an element:
// If newState is provided add/remove theClass accordingly, otherwise toggle theClass
function toggleClass(elem, theClass, newState) {
var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');
var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null));
elem.className=elem.className.replace(matchRegExp, ''); // clear all
if (add) elem.className += ' ' + theClass;
}
See the JSFiddle.
Also see my answer here for creating a new class dynamically.
I use the following vanilla JavaScript functions in my code. They use regular expressions and indexOf but do not require quoting special characters in regular expressions.
function addClass(el, cn) {
var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
c1 = (" " + cn + " ").replace(/\s+/g, " ");
if (c0.indexOf(c1) < 0) {
el.className = (c0 + c1).replace(/\s+/g, " ").replace(/^ | $/g, "");
}
}
function delClass(el, cn) {
var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
c1 = (" " + cn + " ").replace(/\s+/g, " ");
if (c0.indexOf(c1) >= 0) {
el.className = c0.replace(c1, " ").replace(/\s+/g, " ").replace(/^ | $/g, "");
}
}
You can also use element.classList in modern browsers.
The OP question was How can I change an element's class with JavaScript?
Modern browsers allow you to do this with one line of JavaScript:
document.getElementById('id').classList.replace('span1', 'span2')
The classList attribute provides a DOMTokenList which has a variety of methods. You can operate on an element's classList using simple manipulations like add(), remove() or replace(). Or get very sophisticated and manipulate classes like you would an object or Map with keys(), values(), and entries().
Peter Boughton's answer is a great one, but it's now over a decade old. All modern browsers now support DOMTokenList - see https://caniuse.com/#search=classList and even Internet Explorer 11 supports some DOMTokenList methods.
THE OPTIONS.
Here is a little style vs. classList examples to get you to see what are the options you have available and how to use classList to do what you want.
style vs. classList
The difference between style and classList is that with style you're adding to the style properties of the element, but classList is kinda controlling the class(es) of the element (add, remove, toggle, contain), I will show you how to use the add and remove method since those are the popular ones.
Style Example
If you want to add margin-top property into an element, you would do in such:
// Get the Element
const el = document.querySelector('#element');
// Add CSS property
el.style.margintop = "0px"
el.style.margintop = "25px" // This would add a 25px to the top of the element.
classList Example
Let say we have a <div class="class-a class-b">, in this case, we have 2 classes added to our div element already, class-a and class-b, and we want to control what classes remove and what class to add. This is where classList becomes handy.
Remove class-b
// Get the Element
const el = document.querySelector('#element');
// Remove class-b style from the element
el.classList.remove("class-b")
Add class-c
// Get the Element
const el = document.querySelector('#element');
// Add class-b style from the element
el.classList.add("class-c")
Try:
element.className='second'
function change(box) { box.className='second' }
.first { width: 70px; height: 70px; background: #ff0 }
.second { width: 150px; height: 150px; background: #f00; transition: 1s }
<div onclick="change(this)" class="first">Click me</div>
For IE v6-9 (in which classList is not supported and you don't want to use polyfills):
var elem = document.getElementById('some-id');
// don't forget the extra space before the class name
var classList = elem.getAttribute('class') + ' other-class-name';
elem.setAttribute('class', classList);
OK, I think in this case you should use jQuery or write your own Methods in pure JavaScript. My preference is adding my own methods rather than injecting all jQuery to my application if I don't need that for other reasons.
I'd like to do something like below as methods to my JavaScript framework to add few functionalities which handle adding classes, deleting classes, etc. Similar to jQuery, this is fully supported in IE9+. Also my code is written in ES6, so you need to make sure your browser support it or you using something like Babel, otherwise need to use ES5 syntax in your code. Also in this way, we finding element via ID, which means the element needs to have an ID to be selected:
// Simple JavaScript utilities for class management in ES6
var classUtil = {
addClass: (id, cl) => {
document.getElementById(id).classList.add(cl);
},
removeClass: (id, cl) => {
document.getElementById(id).classList.remove(cl);
},
hasClass: (id, cl) => {
return document.getElementById(id).classList.contains(cl);
},
toggleClass: (id, cl) => {
document.getElementById(id).classList.toggle(cl);
}
}
And you can simply use them as below. Imagine your element has id of 'id' and class of 'class'. Make sure you pass them as a string. You can use the utility as below:
classUtil.addClass('myId', 'myClass');
classUtil.removeClass('myId', 'myClass');
classUtil.hasClass('myId', 'myClass');
classUtil.toggleClass('myId', 'myClass');
classList DOM API:
A very convenient manner of adding and removing classes is the classList DOM API. This API allows us to select all classes of a specific DOM element in order to modify the list using JavaScript. For example:
const el = document.getElementById("main");
console.log(el.classList);
<div class="content wrapper animated" id="main"></div>
We can observe in the log that we are getting back an object with not only the classes of the element, but also many auxiliary methods and properties. This object inherits from the interface DOMTokenList, an interface which is used in the DOM to represent a set of space separated tokens (like classes).
Example:
const el = document.getElementById('container');
function addClass () {
el.classList.add('newclass');
}
function replaceClass () {
el.classList.replace('foo', 'newFoo');
}
function removeClass () {
el.classList.remove('bar');
}
button{
margin: 20px;
}
.foo{
color: red;
}
.newFoo {
color: blue;
}
.bar{
background-color: powderblue;
}
.newclass{
border: 2px solid green;
}
<div class="foo bar" id="container">
"Sed ut perspiciatis unde omnis
iste natus error sit voluptatem accusantium doloremque laudantium,
totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et
quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam
voluptatem quia voluptas
</div>
<button onclick="addClass()">AddClass</button>
<button onclick="replaceClass()">ReplaceClass</button>
<button onclick="removeClass()">removeClass</button>
Yes, there are many ways to do this. In ES6 syntax we can achieve easily. Use this code toggle add and remove class.
const tabs=document.querySelectorAll('.menu li');
for(let tab of tabs){
tab.onclick = function(){
let activetab = document.querySelectorAll('li.active');
activetab[0].classList.remove('active')
tab.classList.add('active');
}
}
body {
padding: 20px;
font-family: sans-serif;
}
ul {
margin: 20px 0;
list-style: none;
}
li {
background: #dfdfdf;
padding: 10px;
margin: 6px 0;
cursor: pointer;
}
li.active {
background: #2794c7;
font-weight: bold;
color: #ffffff;
}
<i>Please click an item:</i>
<ul class="menu">
<li class="active"><span>Three</span></li>
<li><span>Two</span></li>
<li><span>One</span></li>
</ul>
Just thought I'd throw this in:
function inArray(val, ary){
for(var i=0,l=ary.length; i<l; i++){
if(ary[i] === val){
return true;
}
}
return false;
}
function removeClassName(classNameS, fromElement){
var x = classNameS.split(/\s/), s = fromElement.className.split(/\s/), r = [];
for(var i=0,l=s.length; i<l; i++){
if(!iA(s[i], x))r.push(s[i]);
}
fromElement.className = r.join(' ');
}
function addClassName(classNameS, toElement){
var s = toElement.className.split(/\s/);
s.push(c); toElement.className = s.join(' ');
}
Just use myElement.classList="new-class" unless you need to maintain other existing classes in which case you can use the classList.add, .remove methods.
var doc = document;
var divOne = doc.getElementById("one");
var goButton = doc.getElementById("go");
goButton.addEventListener("click", function() {
divOne.classList="blue";
});
div{
min-height: 48px;
min-width: 48px;
}
.bordered{
border: 1px solid black;
}
.green{
background: green;
}
.blue{
background: blue;
}
<button id="go">Change Class</button>
<div id="one" class="bordered green">
</div>
TL;DR:
document.getElementById('id').className = 'class'
OR
document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');
That's it.
And, if you really want to know the why and educate yourself then I suggest reading Peter Boughton's answer. It's perfect.
Note:
This is possible with (document or event):
getElementById()
getElementsByClassName()
querySelector()
querySelectorAll()
function classed(el, class_name, add_class) {
const re = new RegExp("(?:^|\\s)" + class_name + "(?!\\S)", "g");
if (add_class && !el.className.match(re)) el.className += " " + class_name
else if (!add_class) el.className = el.className.replace(re, '');
}
Using Peter Boughton's answer, here is a simple cross-browser function to add and remove class.
Add class:
classed(document.getElementById("denis"), "active", true)
Remove class:
classed(document.getElementById("denis"), "active", false)
There is a property, className, in JavaScript to change the name of the class of an HTML element. The existing class value will be replaced with the new one, that you have assigned in className.
<!DOCTYPE html>
<html>
<head>
<title>How can I change the class of an HTML element in JavaScript?</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<h1 align="center"><i class="fa fa-home" id="icon"></i></h1><br />
<center><button id="change-class">Change Class</button></center>
<script>
var change_class = document.getElementById("change-class");
change_class.onclick = function()
{
var icon=document.getElementById("icon");
icon.className = "fa fa-gear";
}
</script>
</body>
</html>
Credit - How To Change Class Name of an HTML Element in JavaScript

JavaScript CSS how to add and remove multiple CSS classes to an element

How can assign multiple css classes to an html element through javascript without using any libraries?
Here's a simpler method to add multiple classes via classList (supported by all modern browsers, as noted in other answers here):
div.classList.add('foo', 'bar'); // add multiple classes
From:
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Examples
If you have an array of class names to add to an element, you can use the ES6 spread operator to pass them all into classList.add() via this one-liner:
let classesToAdd = [ 'foo', 'bar', 'baz' ];
div.classList.add(...classesToAdd);
Note that not all browsers support ES6 natively yet, so as with any other ES6 answer you'll probably want to use a transpiler like Babel, or just stick with ES5 and use a solution like #LayZee's above.
Try doing this...
document.getElementById("MyElement").className += " MyClass";
Got this here...
This works:
myElement.className = 'foo bar baz';
There are at least a few different ways:
var buttonTop = document.getElementById("buttonTop");
buttonTop.className = "myElement myButton myStyle";
buttonTop.className = "myElement";
buttonTop.className += " myButton myStyle";
buttonTop.classList.add("myElement");
buttonTop.classList.add("myButton", "myStyle");
buttonTop.setAttribute("class", "myElement");
buttonTop.setAttribute("class", buttonTop.getAttribute("class") + " myButton myStyle");
buttonTop.classList.remove("myElement", "myButton", "myStyle");
var el = document.getElementsByClassName('myclass')
el[0].classList.add('newclass');
el[0].classList.remove('newclass');
To find whether the class exists or not, use:
el[0].classList.contains('newclass'); // this will return true or false
Browser support IE8+
You can add and remove multiple classes in same way with different in-built methods:
const myElem = document.getElementById('element-id');
//add multiple classes
myElem.classList.add('class-one', 'class-two', 'class-three');
//remove multiple classes
myElem.classList.remove('class-one', 'class-two', 'class-three');
2 great ways to ADD:
But the first way is more cleaner, since for the second you have to add a space at the beginning. This is to avoid the class name from joining with the previous class.
element.classList.add("d-flex", "align-items-center");
element.className += " d-flex align-items-center";
Then to REMOVE use the cleaner way, by use of classList
element.classList.remove("d-grid", "bg-danger");
guaranteed to work on new browsers. the old className way may not, since it's deprecated.
<element class="oneclass" />
element.setAttribute('class', element.getAttribute('class') + ' another');
alert(element.getAttribute('class')); // oneclass another
Since I could not find this answer nowhere:
ES6 way (Modern Browsers)
el.classList.add("foo", "bar", "baz");
just use this
element.getAttributeNode("class").value += " antherClass";
take care about Space to avoid mix old class with new class
Perhaps:
document.getElementById("myEle").className = "class1 class2";
Not tested, but should work.
the Element.className += " MyClass"; is not recommended approach because it will always add these classes whether they were exit or not.
in my case, I was uploading an image file and adding classes to it, now with this each time you upload an image it will add these class whether they exist or not,
the recommended way is Element.classList.add("class1" , "class2" , "class3");
this way will not add extra classes if they already there.
Try this:
function addClass(element, value) {
if(!element.className) {
element.className = value;
} else {
newClassName = element.className;
newClassName+= " ";
newClassName+= value;
element.className = newClassName;
}
}
Similar logic could be used to make a removeClass function.
In modern browsers, the classList API is supported.
This allows for a (vanilla) JavaScript function like this:
var addClasses;
addClasses = function (selector, classArray) {
'use strict';
var className, element, elements, i, j, lengthI, lengthJ;
elements = document.querySelectorAll(selector);
// Loop through the elements
for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
element = elements[i];
// Loop through the array of classes to add one class at a time
for (j = 0, lengthJ = classArray.length; j < lengthJ; j += 1) {
className = classArray[j];
element.classList.add(className);
}
}
};
Modern browsers (not IE) support passing multiple arguments to the classList::add function, which would remove the need for the nested loop, simplifying the function a bit:
var addClasses;
addClasses = function (selector, classArray) {
'use strict';
var classList, className, element, elements, i, j, lengthI, lengthJ;
elements = document.querySelectorAll(selector);
// Loop through the elements
for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
element = elements[i];
classList = element.classList;
// Pass the array of classes as multiple arguments to classList::add
classList.add.apply(classList, classArray);
}
};
Usage
addClasses('.button', ['large', 'primary']);
Functional version
var addClassesToElement, addClassesToSelection;
addClassesToElement = function (element, classArray) {
'use strict';
classArray.forEach(function (className) {
element.classList.add(className);
});
};
addClassesToSelection = function (selector, classArray) {
'use strict';
// Use Array::forEach on NodeList to iterate over results.
// Okay, since we’re not trying to modify the NodeList.
Array.prototype.forEach.call(document.querySelectorAll(selector), function (element) {
addClassesToElement(element, classArray)
});
};
// Usage
addClassesToSelection('.button', ['button', 'button--primary', 'button--large'])
The classList::add function will prevent multiple instances of the same CSS class as opposed to some of the previous answers.
Resources on the classList API:
Can I use
MDN
David Walsh
HTML5 Doctor
Maybe this will help you learn:
//<![CDATA[
/* external.js */
var doc, bod, htm, C, E, addClassName, removeClassName; // for use onload elsewhere
addEventListener('load', function(){
doc = document; bod = doc.body; htm = doc.documentElement;
C = function(tag){
return doc.createElement(tag);
}
E = function(id){
return doc.getElementById(id);
}
addClassName = function(element, className){
var rx = new RegExp('^(.+\s)*'+className+'(\s.+)*$');
if(!element.className.match(rx)){
element.className += ' '+className;
}
return element.className;
}
removeClassName = function(element, className){
element.className = element.className.replace(new RegExp('\s?'+className), '');
return element.className;
}
var out = E('output'), mn = doc.getElementsByClassName('main')[0];
out.innerHTML = addClassName(mn, 'wow');
out.innerHTML = addClassName(mn, 'cool');
out.innerHTML = addClassName(mn, 'it works');
out.innerHTML = removeClassName(mn, 'wow');
out.innerHTML = removeClassName(mn, 'main');
}); // close load
//]]>
/* external.css */
html,body{
padding:0; margin:0;
}
.main{
width:980px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<div id='output'></div>
</div>
</body>
</html>
addClass(element, className1, className2){
element.classList.add(className1, className2);
}
removeClass(element, className1, className2) {
element.classList.remove(className1, className2);
}
removeClass(myElement, 'myClass1', 'myClass2');
addClass(myElement, 'myClass1', 'myClass2');
ClassList add
var dynamic=document.getElementById("dynamic");
dynamic.classList.add("red");
dynamic.classList.add("size");
dynamic.classList.add("bold");
.red{
color:red;
}
.size{
font-size:40px;
}
.bold{
font-weight:800;
}
<div id="dynamic">dynamic css</div>

How to 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?
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.
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.
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..
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
jsPerf Test Case: Adding a Class
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")
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");
2 different ways to add class using JavaScript
JavaScript provides 2 different ways by which you can add classes to HTML elements:
Using element.classList.add() Method
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
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>
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;
}
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.
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 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.)
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);
}
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
})
}
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');
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 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>
This might be helpful for WordPress developers etc.
document.querySelector('[data-section="section-hb-button-1"] .ast-custom-button').classList.add('TryMyClass');
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.
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)
}
}
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";
})
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()
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>
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');
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.
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"));
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
In YUI, if you include yuidom, you can use
YAHOO.util.Dom.addClass('div1','className');
HTH

Categories

Resources