How to Change Element’s Class With JavaScript

Often web developers need to change the class name of one or more HTML elements on their web pages. This is because various JavaScript functions and CSS styles are attached to class names. So by changing class names of elements, developers can easily change the functionality & appearance of their web pages. Sometimes, these kind of changes need to be triggered when events like button clicks are fired. In this article, we will learn how to change element’s class with JavaScript. You can use any of these methods.

How to Change Element’s Class With JavaScript

There are several ways to easily change element’s class with JavaScript. Let us look at them one by one. Let us say you have the following HTML element with id and class attributes already defined.

<div id='div_id' class='div_class'>hello world</div>

1. HTML5 Solution

Most modern web browsers such as Chrome, Firefox, Edge, Safari, Opera support HTML5. In this version of HTML, each element already has a property classList that contains a list of all class names already assigned to the element. This classList property further supports methods like add(), remove(), contains() and toggle() to add, remove, check and toggle class names. Let us learn more about them.

You can easily select an element using document.getElementById() function. We will use it to select the element and use its classList() property.

Here is the code to select our div and add class ‘my_div’ to it.

document.getElementById("div_id").classList.add('my_div');

Once you run the above code, your div will have two classes div_class as well as my_div. If your div already has my_div class present, then it will not give any error or warning. Every element can have only unique class names so it will not once again the my_div class name either.

Here is how to remove the class ‘my_div’ from it.

document.getElementById("div_id").classList.remove('my_div');

Once you run the above code, your div will only have class div_class and not my_div in it. If my_div class is not present and you run the above code, it will not give any error.

If you want to check if an element contains a specific class name or not, then you can call contains() function.

document.getElementById("div_id").classList.contains('my_div');

The above code will return True or False depending on whether the class name is present or not.

You can also toggle a class name for a given element using toggle() function.

document.getElementById("div_id").classList.toggle('my_div');

The above code will first check if the class my_div is present or not, and if present, it will remove the class. If it is not present, then it will add the class. In both cases, the other class names are left unchanged. This is generally useful to toggle the class name of an element on calling an event such as button click. Based on the toggling of class name of an element, you can change CSS style of the element.

<script type="text/javascript">
function changeClass(){
document.getElementById("div_id").classList.toggle('my_div');
}
</script>
...
<button onClick="changeClass()">My Button</button>
<div id='div_id' class='div_class'>hello world</div>

In this example, we have a button a div on web page. We have added a click event handler for the button. In this event handler, we basically toggle the class name of div.

2. Set All Classes for Element

All the above methods we have seen so far, work well on web browser versions that support HTML5. Some of the older web browsers such as IE may not support it. In such cases, you can use a more basic JavaScript code. The approach remains the same. First, we select the target element, then use a function or property setting to change its class name.

Every HTML element supports a property className that you can use to set a class name to an element.

document.getElementById("div_id").className = 'my_div';

Please note, the above code will completely replace all existing classes of the element with my_div. If you want, you can also specify multiple class names in the above code to set one or more classes. Here is an example to set class name to ‘my_div’ and ‘my_div2’. You need to mention them in a space-separated format.

document.getElementById("div_id").className = 'my_div my_div2';

3. Add New Class to Element

If you want to simply add a new class name without changing any of the existing class names, use the following code.

document.getElementById("div_id").className += ' my_div';

Please note a couple of things above. Here we use += operator, instead of = operator, since we need to append a new class name, instead of overwriting existing class names. Secondly, in the string containing class name, we need to provide a space before the new class name (‘ my_div’ instead of ‘my_div’).

4. Remove Class From Element

We need to use replace() function to remove a class name from an element. Here is the code to remove my_div class.

document.getElementById("div_id").className =   document.getElementById("div_id").className.replace
( /(?:^|\s)my_div(?!\S)/g , '' )

In the replace function, we need to use a regular expression to match the class name and replace it with empty string. In the above code, replace div_id with the ID of the element whose class you want to remove. Replace my_div with the class name you want to remove.

5. Check if Class Exists

Sometimes, you simply need to check if an element contains a specific class. In this case, you can use the match() function as shown below.

document.getElementById("div_id").className.match(/(?:^|\s)my_div(?!\S)/)

The above code again uses a different regular expression. Replace my_div with the class name you want to check and replace div_id with the id of the element for whom you want to run this code.

6. Change Class Using jQuery

You can also use popular jQuery library that makes it very easy to select an element and change its class names.

Only you will need to include jQuery library file in your web page. jQuery provides addClass(), removeClass() and hasClass() functions to add new class, remove class and check if an element has a class respectively. Here is the code to add class ‘my_div’ to element with id=div_id. You can select the div using $(‘#div_id’) selector.

$('#div_id').addClass('my_div');

Here is the code to remove the class ‘my_div’ from our div.

$('#div_id').removeClass('my_div');

Here is the code to check if the element has a class my_div.

$('#div_id').hasClass('my_div');

You can also use toggleClass() function to toggle the class of the element.

$('#div_id').toggleClass('my_div');

7. Change class of multiple elements

So far, we have seen all examples where we change the class of one element only. But what if you want to change class of multiple elements? You can easily do that by simply changing the selector. Here is the code to add class ‘my_div’ to all elements with class ‘div_class’ in jQuery.

$('.div_class').addClass('my_div');

The same code using plain JavaScript.

var items = document.getElementsByClassName("div_class");
for(var i=0; i < items.length; i++){
items[i].className+='my_div';
}

Here we need to use getElementsByClassName() function to obtain a collection of elements having a specific class name. Since it is an array-like result, we need to loop through its items and change the class name for each item. We cannot directly set their className property.

The main difference between jQuery and JavaScript here is that jQuery functions automatically work on all items whether the CSS selector returns one or multiple items. So you can use the same functions and code for single or multiple elements. In case of JavaScript, you need to loop through the result, if your selection returns multiple items. So you need to change your approach depending on whether you target one or multiple elements.

Conclusion

In this article, we have learnt many different ways to change HTML element’s class in JavaScript as well as jQuery. You can use any of these methods depending on your requirement. Although we have provided solutions for a div, you can use it for all elements, since we are using CSS selectors. The key part is to correctly select the desired HTML element, using CSS selector. Thereafter, you can use any of the solutions to alter the element’s class name. Among them, using HTML5 solutions is the easiest, whereas if you also want to support old web browsers then go for the basic JavaScript solutions mentioned above. If your website is already using jQuery, then we recommend using jQuery functions since they are very easy to use and versatile.

Also read:

How to Set Cellpadding & Cellspacing in CSS
How to Horizontally Center Div in CSS
How to Change HTML Input’s Placeholder Color

Leave a Reply

Your email address will not be published. Required fields are marked *