Html source code

How to change a CSS class in JavaScript

Regular web sites may only be styled with the help of plain CSS rules. But, if you are making a dynamic web site with some forms, windows, visual effects, or any other similar functionality, then you may need to modify CSS classes at runtime.

Such a task is not complicated in JavaScript, there are many different options that can be used in a web project. This article lists all the possible methods, and you can choose a solution that is the most applicable in your specific situation.

Plain JavaScript method to change a CSS class

For most of the projects, for example, built in Angular, React or Vue, you can use plain JavaScript code to modify a class for the desired HTML element. This solution is stable, even if you change a framework or upgrade JS libraries, it's likely that your code will work correctly.

Also, JavaScript is a mature language with a long history, most of the features are backward compatible, as a result, using such a method may be a wise decision.

Changing the className property

Each JavaScript element contains the className property and you can modify it according to your requirements. All the changes will be reflected in the class attribute that belongs to the target HTML element.

Following is a very simple HTML code that will be used as a starting point to show how to change the CSS class.

<div id="content" class="container">Hello World</div>

Now, we need to find the desired HTML element within the document tree. We can use the getElementById() function for that purpose, you just need to pass the ID as an argument.

Then, we assign the desired class into the className property.

document.getElementById('content').className = 'message';

The very important note is that all the existing classes will be overridden by the new value.

See how the new HTML code will look:

<div id="content" class="message">Hello World</div>

However, if you'd like to keep existing CSS classes on the specific HTML element, then you can use the += operator to modify contents of the className property.

document.getElementById('content').className += 'notice';

But, it is worth mentioning that the above code does not check if the specific CSS class already exists in the className property.

The final HTML code will look like the following:

<div id="content" class="container message notice">Hello World</div>

Using the classList property

There is a modern native JavaScript functionality that allows to manipulate CSS classes in a convenient way. You don't need to work with the strings and space characters directly.

The Element class contains the classList property, which implements the DOMTokenList interface. The most important methods are listed below and you can use them to easily change a CSS class with just a single line of code.

The first method that we will describe is add(), it has to be used if you need to add some CSS class to a specific element. Please see how this can be done below.

document.getElementById('content').classList.add('message');

Also, you can pass as many classes as you need into the function call, the code sample is given below.

document.getElementById('content').classList.add('message', 'notice', 'status');

To remove some class from the desired HTML element, you need to call the remove() method.

document.getElementById('content').classList.remove('message');

However, if you don't know if the given class is already inside of the list, or you are building a dynamic application and need to switch class state depending on some condition, then you can use the toggle() method. It will add or remove the specified CSS class depending on it's existence in a given list.

document.getElementById('content').classList.toggle('message');

The classList property also contains a method that allow to replace existing class in a list, see it in the example below:

document.getElementById('content').classList.replace('container', 'message');

It is worth mentioning that you can directly test if the class exists in the list, to perform such an operation, you have to call the contains() method. Then, on a successful check, you can execute the desired code block.

if (document.getElementById('content').classList.contains('message')) {
    console.log('Class exists');
}

Modifying the class attribute directly

As you already know, the "class" keyword is a regular HTML attribute, and it means that you can use the relevant JavaScript functions to manipulate the state of the given attribute.

This solution is not suitable for most applications, however you can use it in very specific scenarios, like if you need to get the raw class string, or you have to remove all the CSS classes altogether with the attribute itself.

The setAttribute() method can be used to set the state of the attribute. The usage is pretty straightforward, you need to provide the attribute name, which is "class" in our case, then you have to specify the class names as a regular string value. Please see it in our example below.

document.getElementById('content').setAttribute('class', 'message');

To remove the attribute from the desired HTML element, you have to call the removeAttribute() method with just a single argument, which is the attribute name.

document.getElementById('content').removeAttribute('class');

You can also get a value for the given attribute, to do this you need to call the getAttribute() method, code sample is provided below.

document.getElementById('content').getAttribute('class');

Finally, it's also possible to detect if the target HTML element contains the specific attribute. You may call the hasAttribute() function with the attribute name and it will return either true or false state.

if (document.getElementById('content').hasAttribute('class')) {
    console.log('Attribute exists');
}

Using the jQuery library to change a CSS class

There are many web applications and sites that use the jQuery library. And if you are working on such a project, then it may be wise to use the relevant methods which are provided by this library. Your code will be compact and easy to read, since you don't need to use complex JavaScript language features to find the desired element within the HTML document tree.

To show how to work with the jQuery library, we will write a code that interacts with a very simple HTML structure, that is shown below:

<div id="content" class="container">Hello World</div>

To add a class to the element, you have to find that element and then call the addClass() method.

$('#content').addClass('message');

As a result, the generated HTML code should look like the following:

<div id="content" class="container message">Hello World</div>

Please pay attention that the addClass() function does not add a CSS class if it's already in the list of element's classes, it means that there will be no duplicates.

Also, you can easily remove a class by calling the removeClass() method.

$('#content').removeClass('message');

If you are not sure if the CSS class is attached to the HTML element, then you may use the toggle() method. It will determine the state of the given class and will switch it accordingly.

$('#content').toggleClass('message');

The jQuery library also contains the hasClass() method that allows checking if the element already has a specific class, please see how to use it below.

if ($('#content').hasClass('message')) {
    console.log('Class exists');
}

Conclusion

There are many different methods that can be used in your project to manipulate CSS classes. Each solution is unique and is suitable in a specific case only.

Before making the project, you have to determine which option to use, since the decision depends on many factors, for example, performance, integrated frameworks, etc.

As you see, it's possible to work directly with the CSS attributes. Usually, this is a case in large and complex native applications, where you may need to obtain raw values from the document tree.

On the other hand, the classList method is a choice for dynamic web applications with a lot of windows, popup forms or various visual effects. The jQuery library is widely used in regular web sites or small web applications, as a result, it's wise to know how to work with this library.

Related Articles

Sticky memo notes

Box shadow in CSS

Mobile and laptop devices

Responsive font size in CSS

Comments

Leave a Reply

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