How to change an element's class with JavaScript

October 13, 2022 No comments javascript html dom

Introduction

In JavaScript, we may wish to change an element's class. In this post, we'll look at how to do it.

How to change an element's class with JavaScript

To change an element's class with JavaScript you can use the classList property that provides methods for classes manipulation:

var el = document.getElementById("elementID");

el.classList.add('my-class'); // adding class 'my-class' for element with id = elementID

el.classList.remove('my-class'); // removing class 'my-class' for element with id = elementID

if (el.classList.contains('my-class')) // check if element with id = elementID contains class 'my-class'

el.classList.toggle('my-class'); // remove class 'my-class' for element with ID = elementID if that class exists, or add it if not

To change class in JavaScript we can also use className property

Set the className property to replace all current classes with one or more new classes:

document.getElementById("elementID").className = "my-class";

To add a my-class class to an element, use the following code:

document.getElementById("elementID").className += "my-class";

To remove a my-class class from an element, use the following code:

document.getElementById("elementID").className =
   document.getElementById("elementID").className.replace( /(?:^|\s)my-class(?!\S)/g , '' );

To check if an element contains a specific class:

if (document.getElementById("elementID").className.match(/(?:^|\s)my-class(?!\S)/) )

Conclusion

In this short article, we described how to change an element's class with JavaScript.

{{ message }}

{{ 'Comments are closed.' | trans }}