Skip to content

October 11, 2015

JavaScript for manipulation with CSS class names

Modern browsers are providing a support of read-only property which returns a live DOMTokenList of the class attributes of the element, which is element.classList, which is actually a list of CSS classes of element, also we have methods for making manipulation with CSS class names and getting their number.

Let’s have a look what we can use in plain JavaScript for manipulating with CSS class names:

  • element.classList — this way we can get a list of CSS class names of element, it’s actually an object which has ‘like array’ behaviour and contains elements with CSS class names. We can render this list in HTML, using innerHTML for example and it will be string with elements separated with space
  • element.classList.length — this is a read-only property which contains a number of CSS class names of the element
  • element.classList.toggle(className) — this is a method for toggling CSS class name which is a parameter className (if this CSS class name exists, it will be removed, if not — it will be added), like in jQuery $(‘.element’).toggle(className);
  • element.classList.add(className) — this method is obviously for adding CSS class name
  • element.classList.remove(className) — and this for deleteng CSS class name
  • element.classList.contains(className) — method for checking if element has CSS class name from className parameter, it returns boolean value (true or false.
  • element.classList.item(index) — method for getting CSS class name by index. Because we have ‘like array’ object we can get any of element of classList which is actually contains name of CSS class using index, because each of element has index.

Toggle CSS class name of element

Let’s start with adding some JavaScript for manipulation with CSS class names using toggle method.

We will add HTML first. It contains our element with CSS class ‘element’, the CSS class names of this element will be updated by JavaScript. Next thing is the label and the checkbox for toggling ‘active’ class name on our element.

<div class="element">
    Element
</div>
<label>
    Toggle Class name 'active'
    <input type="checkbox" class="switcher"/>
</label>

And CSS for having some indication if our ‘active’ CSS class name was toggled on element. Red color will be added to the element if it will contain ‘active’ CSS class. Also let’s add to label element ‘display: block’ style.

body {
    font: normal 0.8rem/2 Helvetica, sans-serif;
}
.active {
    color: red;
}
label {
    color: blue;
    display: block;   
}

Then, we can add JavaScript. First, we can get element by using the querySelector method to get our DOM element:

var element = document.querySelector('.element');

Next we can add the function for toggling CSS class name. It will take two parameters: the first one is our DOM element and the second, is CSS class name. When this function will be invoked by some event, it will toggle CSS class name.

// Methods for working with CSS classes via className property
var toggleClassName = function(element, className) {
    element.classList.toggle(className);
};

Let’s add event listener to our checkbox, which will call our function, when ‘change’ event happens on our checkbox.

// Event listeners
// Listen to change of checkbox "Toggle Class name 'active'"
var inputSwitcher = document.querySelector('.switcher');
inputSwitcher.addEventListener('change', function() {
    toggleClassName(element, 'active');
});

As you can see it’s really easy to use manipulation with CSS class names using classList in vanilla JavaScript, in terms of using for example ‘expand/collapse’ functionality across your applications.

Getting all CSS class names of element and the number of CSS classes

We can add to our example some additional information which will be updated after toggling of CSS class name.

Let’s add two panels with additional information using HTML:

<div>CSS classes: <span class="element-classes"></span></div>
<div>Number of CSS classes: <span class="element-classes-number"></span></div>

This function will return number of CSS classes, which is actually the length property of ‘array like’ classList object:

var getNumberOfClassNames = function(element) {
	return element.classList.length;   
}

This function will render CSS class names of our element:

// Get element for showing of list of CSS class names
var elementClasses = document.querySelector('.element-classes');
var showClassNames = function(element, panel) {
    panel.innerHTML = element.classList;
};

This function will render a number of CSS classes of our element, using getNumberOfClassNames function, which actually return a number:

// Get element for showing number of CSS class names
var elementClassesNumber = document.querySelector('.element-classes-number');
var showElementClassesNumber = function(element, panel) {
    panel.innerHTML = getNumberOfClassNames(element);
};

This function will render our information. After defining this function we are invoking it, so it will render actual state, which is supposed to be our default values: ‘element’ class name, and the number is 1.

// Render updated information
var renderInformation = function() { 
    showClassNames(element, elementClasses);
    showElementClassesNumber(element, elementClassesNumber);
};
renderInformation();

Also we need to refresh this information after toggling the class name, so we need to update our event listener function under toggling checkbox with adding of invoking of the renderInformation function:

inputSwitcher.addEventListener('change', function() {
    toggleClassName(element, 'active');
    renderInformation();
});

Let’s take a look to the result:

Adding, removing, checking and getting by index CSS class names

With the same approach, that was used for building toggling functionality, previous example can be extended to the full version, with all available features for manipulating with CSS class names using classList property:

It contains additional fields, and functionalty. Using that you can:

  • Add custom CSS class name. Try to add ‘disabled’ class name, which is predefined in CSS, to see how it will affect the element
  • Remove one of existing CSS class names. The dropdown contains only existing class names.
  • Check if suggested CSS class name is exists like property of the element.
  • Get CSS class name by index. It this case order of CSS classes matters.

You can play with this sandbox to see how it works and affects element.

Browsers support

classList supported by all modern browsers (IE10 and above), also you can use the polyfill for IE8 and above.