Peter Eberle
Peter Eberle

Reputation: 1181

How to add and remove classes in Javascript without jQuery

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

Upvotes: 115

Views: 293170

Answers (13)

Kerry Johnson
Kerry Johnson

Reputation: 1033

You can also do

elem.classList[test ? 'add' : 'remove']('class-to-add-or-remove');

Instead of

if (test) {
    elem.classList.add('class-to-add-or-remove');
} else {
    elem.classList.remove('class-to-add-or-remove');
}

Upvotes: 4

Milos
Milos

Reputation: 31

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

})
}

Upvotes: 0

connexo
connexo

Reputation: 56783

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

Upvotes: 18

NikzJon
NikzJon

Reputation: 954

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

Upvotes: 2

Nalan Madheswaran
Nalan Madheswaran

Reputation: 10572

Try this:

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

  }

Upvotes: 4

Fahim Shah
Fahim Shah

Reputation: 21

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

Upvotes: 2

Dan Bray
Dan Bray

Reputation: 7832

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/

Upvotes: 60

Chris Ferdinandi
Chris Ferdinandi

Reputation: 1962

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

Upvotes: 31

Yonatan Ayalon
Yonatan Ayalon

Reputation: 2045

Add & Remove Classes (tested on IE8+)

Add trim() to IE (taken from: .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/

Upvotes: 4

Gil
Gil

Reputation: 1804

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.

Upvotes: 0

zavg
zavg

Reputation: 11071

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.

Upvotes: 6

jongo45
jongo45

Reputation: 3090

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

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

Upvotes: 16

Shoaib Chikate
Shoaib Chikate

Reputation: 8973

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

Upvotes: 210

Related Questions