How to add and remove classes in Javascript without jQuery

JavascriptHtml

Javascript Problem Overview


I'm looking for a fast and secure way to add and remove classes from an html element without jQuery.
It also should be working in early IE (IE8 and up).

Javascript Solutions


Solution 1 - Javascript

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

Note: but not supported in IE <= 9 or Safari <=5.0

Solution 2 - Javascript

The following 3 functions work in browsers which don't support classList:

function hasClass(el, className)
{
    if (el.classList)
	    return el.classList.contains(className);
	return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
}

function addClass(el, className)
{
	if (el.classList)
    	el.classList.add(className)
	else if (!hasClass(el, className))
    	el.className += " " + className;
}

function removeClass(el, className)
{
	if (el.classList)
		el.classList.remove(className)
	else if (hasClass(el, className))
	{
    	var reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
		el.className = el.className.replace(reg, ' ');
	}
}

https://jaketrent.com/post/addremove-classes-raw-javascript/

Solution 3 - Javascript

For future friendliness, I second the recommendation for classList with polyfill/shim: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#wrapper

var elem = document.getElementById( 'some-id' );
elem.classList.add('some-class'); // Add class
elem.classList.remove('some-other-class'); // Remove class
elem.classList.toggle('some-other-class'); // Add or remove class
if ( elem.classList.contains('some-third-class') ) { // Check for class
    console.log('yep!');
}

Solution 4 - Javascript

classList is available from IE10 onwards, use that if you can.

element.classList.add("something");
element.classList.remove("some-class");

Solution 5 - Javascript

I'm baffled none of the answers here prominently mentions the incredibly useful DOMTokenList.prototype.toggle method, which really simplifies alot of code.

E.g. you often see code that does this:

if (element.classList.contains(className) {
  element.classList.remove(className)
} else {
  element.classList.add(className)
}

This can be replaced with a simple call to

element.classList.toggle(className)

What is also very helpful in many situations, if you are adding or removing a class name based on a condition, you can pass that condition as a second argument. If that argument is truthy, toggle acts as add, if it's falsy, it acts as though you called remove.

element.classList.toggle(className, condition) // add if condition truthy, otherwise remove

Solution 6 - Javascript

To add class without JQuery just append yourClassName to your element className

document.documentElement.className += " yourClassName";

To remove class you can use replace() function

document.documentElement.className.replace(/(?:^|\s)yourClassName(?!\S)/,'');

Also as @DavidThomas mentioned you'd need to use the new RegExp() constructor if you want to pass class names dynamically to the replace function.

Solution 7 - Javascript

Add & Remove Classes (tested on IE8+)

Add trim() to IE (taken from: https://stackoverflow.com/questions/2308134/trim-in-javascript-not-working-in-ie)

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

Add and Remove Classes:

function addClass(element,className) {
  var currentClassName = element.getAttribute("class");
  if (typeof currentClassName!== "undefined" && currentClassName) {
    element.setAttribute("class",currentClassName + " "+ className);
  }
  else {
    element.setAttribute("class",className); 
  }
}
function removeClass(element,className) {
  var currentClassName = element.getAttribute("class");
  if (typeof currentClassName!== "undefined" && currentClassName) {
    
    var class2RemoveIndex = currentClassName.indexOf(className);
    if (class2RemoveIndex != -1) {
        var class2Remove = currentClassName.substr(class2RemoveIndex, className.length);
        var updatedClassName = currentClassName.replace(class2Remove,"").trim();
        element.setAttribute("class",updatedClassName);
    }
  }
  else {
    element.removeAttribute("class");	
  }	
}

Usage:

var targetElement = document.getElementById("myElement");

addClass(targetElement,"someClass");

removeClass(targetElement,"someClass");

A working JSFIDDLE: http://jsfiddle.net/fixit/bac2vuzh/1/

Solution 8 - Javascript

Try this:

  const element = document.querySelector('#elementId');
  if (element.classList.contains("classToBeRemoved")) {
    element.classList.remove("classToBeRemoved");

  }

Solution 9 - Javascript

I'm using this simple code for this task:

CSS Code

.demo {
     background: tomato;
     color: white;
}

Javascript code

function myFunction() {
    /* Assign element to x variable by id  */
    var x = document.getElementById('para);

    if (x.hasAttribute('class') {      
        x.removeAttribute('class');     
    } else {
        x.setAttribute('class', 'demo');
    }
}

Solution 10 - Javascript

Updated JS Class Method

The add methods do not add duplicate classes and the remove method only removes class with exact string match.

const addClass = (selector, classList) => {
  const element = document.querySelector(selector);
  const classes = classList.split(' ')
  classes.forEach((item, id) => {
    element.classList.add(item)
  })
}

const removeClass = (selector, classList) => {
  const element = document.querySelector(selector);
  const classes = classList.split(' ')
  classes.forEach((item, id) => {
    element.classList.remove(item)
  })
}

addClass('button.submit', 'text-white color-blue') // add text-white and color-blue classes
removeClass('#home .paragraph', 'text-red bold') // removes text-red and bold classes

Solution 11 - Javascript

When you remove RegExp from the equation you leave a less "friendly" code, but it still can be done with the (much) less elegant way of split().

function removeClass(classString, toRemove) {
    classes = classString.split(' ');
    var out = Array();
    for (var i=0; i<classes.length; i++) {
        if (classes[i].length == 0) // double spaces can create empty elements
            continue;
        if (classes[i] == toRemove) // don't include this one
            continue;
        out.push(classes[i])
    }
    return out.join(' ');
}

This method is a lot bigger than a simple replace() but at least it can be used on older browsers. And in case the browser doesn't even support the split() command it's relatively easy to add it using prototype.

Solution 12 - Javascript

Just in case someone needs to toggle class on click and remove on other elements in JS only. You can try to do following :

var accordionIcon = document.querySelectorAll('.accordion-toggle');
//add only on first element, that was required in my case 
accordionIcon[0].classList.add('close');
for (i = 0; i < accordionIcon.length; i++) {

accordionIcon[i].addEventListener("click", function(event) {
for (i = 0; i < accordionIcon.length; i++) {

if(accordionIcon[i] !== event.target){
accordionIcon[i].classList.remove('close');
}
event.target.classList.toggle("close");
}

})
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeter EberleView Question on Stackoverflow
Solution 1 - JavascriptShoaib ChikateView Answer on Stackoverflow
Solution 2 - JavascriptDan BrayView Answer on Stackoverflow
Solution 3 - JavascriptChris FerdinandiView Answer on Stackoverflow
Solution 4 - Javascriptjongo45View Answer on Stackoverflow
Solution 5 - JavascriptconnexoView Answer on Stackoverflow
Solution 6 - JavascriptzavgView Answer on Stackoverflow
Solution 7 - JavascriptYonatan AyalonView Answer on Stackoverflow
Solution 8 - JavascriptNalan MadheswaranView Answer on Stackoverflow
Solution 9 - JavascriptFahim ShahView Answer on Stackoverflow
Solution 10 - JavascriptNikzJonView Answer on Stackoverflow
Solution 11 - JavascriptGilView Answer on Stackoverflow
Solution 12 - JavascriptMilos View Answer on Stackoverflow