ā¹ļø Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.3 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://www.sitepoint.com/add-remove-css-class-vanilla-js/ |
| Last Crawled | 2026-03-31 18:48:01 (8 days ago) |
| First Indexed | 2016-09-28 20:39:00 (9 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Quick Tip: Add or Remove a CSS Class with Vanilla JavaScript ā SitePoint |
| Meta Description | Yaphi Berhanu demonstrates two different methods for adding and removing a CSS class to DOM elements with vanilla JavaScript. No jQuery required! |
| Meta Canonical | null |
| Boilerpipe Text | Yaphi Berhanu
Published in
September 28, 2016
Ā·
Updated:
November 7, 2024
Share this article
Key Takeaways
Adding or removing CSS classes with JavaScript can be useful to alter page elements in response to user actions, such as showing or hiding menus, highlighting form errors, or animating elements.
The JavaScript properties āclassNameā and āclassListā can be used to manipulate classes; āclassNameā is more widely compatible, while āclassListā is more modern and convenient.
Functions can be created to add or remove classes from elements using either the āclassNameā or āclassListā properties. These functions can take in a string selector or the elements themselves, loop through the elements, and add or remove the specified class.
The classList property, supported by browsers from IE10 and up, offers a range of methods to manipulate classes, including āaddā, āremoveā, and ātoggleā. This property simplifies the process of adding or removing classes compared to the āclassNameā property.
Sometimes you need to add or remove a CSS class with JavaScript, and you donāt want to include an entire library like jQuery to do it.
This is useful in situations when you want your page elements to change in response to user actions.
Example uses include:
Showing or hiding a menu
Highlighting a form error
Showing a dialog box
Showing different content in response to a selection
Animating an element in response to a click
There are two JavaScript properties that let you work with classes:
className
and
classList
. The former is
widely compatible
, while the latter is
more modern
and convenient. If you donāt need to support IE 8 and 9, you can skip
className
.
Weāll start with the compatible version first.
Note: This tutorial assumes some familiarity with JavaScript concepts like functions and variables.
Modifying Classes the Compatible Way
The JavaScript
className
property lets you access the
class
attribute of an HTML element. Some string manipulation will let us add and remove classes.
Weāll access HTML elements using
querySelectorAll()
, which is compatible with browsers from IE8 and up.
Add a Class
To add a class, weāll write a function that takes in the elements we want to change and adds a specified class to all of them.
function addClass(elements, myClass) {
// if there are no elements, we're done
if (!elements) { return; }
// if we have a selector, get the chosen elements
if (typeof(elements) === 'string') {
elements = document.querySelectorAll(elements);
}
// if we have a single DOM element, make it an array to simplify behavior
else if (elements.tagName) { elements=[elements]; }
// add class to all chosen elements
for (var i=0; i<elements.length; i++) {
// if class is not already found
if ( (' '+elements[i].className+' ').indexOf(' '+myClass+' ') < 0 ) {
// add class
elements[i].className += ' ' + myClass;
}
}
}
Youāll see how the function works soon, but to watch the function in action, feel free to use this CSS:
.red {
background: red;
}
.highlight {
background: gold;
}
ā¦and this HTML:
<div id="iddiv" class="highlight">ID div</div>
<div class="classdiv">Class div</div>
<div class="classdiv">Class div</div>
<div class="classdiv">Class div</div>
Here are some usage examples of the function itself:
addClass('#iddiv','highlight');
addClass('.classdiv','highlight');
addClass(document.getElementById('iddiv'),'highlight');
addClass(document.querySelector('.classdiv'),'highlight');
addClass(document.querySelectorAll('.classdiv'),'highlight');
Notice that you can identify the HTML elements you want to change through a selector or you can directly pass in the elements themselves.
How Our addClass Function Works
Our
addClass
function first takes two parameters: the HTML elements we want to modify and the class we want to add. Our goal is to loop through each HTML element, make sure the class is not already there, and then add the class.
First, if the list of elements is empty, our function has nothing left to do, so we can get out early.
// if there are no elements, we're done
if (!elements) { return; }
Next, if weāve chosen to identify our HTML elements through a selector such as
#iddiv
or
.classdiv
, then we can use
querySelectorAll()
to grab all of our desired elements.
// if we have a selector, get the chosen elements
if (typeof(elements) === 'string') {
elements = document.querySelectorAll(elements);
}
However, if DOM elements are fed into the function directly, we can loop through them. If thereās a single DOM element (rather than a list), weāll make it an array so we can use the same loop and simplify our code. We can tell if thereās only one element because an element has a
tagName
property, while a list does not.
// if we have a single DOM element, make it an array to simplify behavior
else if (elements.tagName) { elements=[elements]; }
Now that we have our elements in a format we can loop over, weāll go through each one, check if the class is already there, and if not, weāll add the class.
// add class to all chosen elements
for (var i=0; i<elements.length; i++) {
// if class is not already found
if ( (' '+elements[i].className+' ').indexOf(' '+myClass+' ') < 0 ) {
// add class
elements[i].className += ' ' + myClass;
}
}
Notice weāre adding a space at the beginning and end in order to simplify the pattern weāre looking for and avoid needing a regular expression.
In any case, weāre done ā you can now add a class!
Remove a Class
To remove a class, we can use the following function:
function removeClass(elements, myClass) {
// if there are no elements, we're done
if (!elements) { return; }
// if we have a selector, get the chosen elements
if (typeof(elements) === 'string') {
elements = document.querySelectorAll(elements);
}
// if we have a single DOM element, make it an array to simplify behavior
else if (elements.tagName) { elements=[elements]; }
// create pattern to find class name
var reg = new RegExp('(^| )'+myClass+'($| )','g');
// remove class from all chosen elements
for (var i=0; i<elements.length; i++) {
elements[i].className = elements[i].className.replace(reg,' ');
}
}
Most of this
removeClass
function works the same way as our
addClass
function; by gathering the desired HTML elements and looping through them. The only difference is the part where the class gets removed.
Hereās the class removal in more detail:
// create pattern to find class name
var reg = new RegExp('(^| )'+myClass+'($| )','g');
// remove class from all chosen elements
for (var i=0; i<elements.length; i++) {
elements[i].className = elements[i].className.replace(reg,' ');
}
First, we create a regular expression to look for all instances of our desired class. The expression
'(^| )'+myClass+'($| )'
means the beginning or a space followed by
myClass
followed by the end or a space. The
'g'
means global match, which means find all instances of the pattern.
Using our pattern, we replace the class name with a space. That way, class names in the middle of the list will remain separated, and thereās no harm done if the removed class is on the ends.
Modifying Classes the Modern Way
Browsers from IE10 and up support a property called
classList
, which makes an elementās classes much easier to deal with.
In
a previous article
, Craig Buckler provided a list of things
classList
can do:
The following properties are available:
length ā the number of class names applied
item(index) ā the class name at a specific index
contains(class) ā returns true if a node has that class applied
add(class) ā applies a new class to the node
remove(class) ā removes a class from the node
toggle(class) ā removes or adds a class if itās applied or not applied respectively
We can use this in preference to the clunkier className property:
document.getElementById("myelement").classList.add("myclass");
Letās use this information to create functions that add and remove classes from all elements that match a selector.
These functions will get all desired elements, loop through them, and add or remove a class to each one.
Add Class
function addClass(selector, myClass) {
// get all elements that match our selector
elements = document.querySelectorAll(selector);
// add class to all chosen elements
for (var i=0; i<elements.length; i++) {
elements[i].classList.add(myClass);
}
}
// usage examples:
addClass('.class-selector', 'example-class');
addClass('#id-selector', 'example-class');
Remove class
function removeClass(selector, myClass) {
// get all elements that match our selector
elements = document.querySelectorAll(selector);
// remove class from all chosen elements
for (var i=0; i<elements.length; i++) {
elements[i].classList.remove(myClass);
}
}
// usage examples:
removeClass('.class-selector', 'example-class');
removeClass('#id-selector', 'example-class');
Conclusion
Weāve covered how to add and remove classes through
className
(the compatible way) and
classList
(the more modern way).
When you can control CSS classes through JavaScript, you unlock a lot of functionality including content display updates, animations, error messages, dialogs, menus, and more.
I hope this article has been helpful, and if you have any questions or thoughts, please feel free to share them in the comments.
Frequently Asked Questions (FAQs) on Adding and Removing CSS Classes with Vanilla JS
What is the purpose of adding or removing CSS classes using Vanilla JS?
The primary purpose of adding or removing CSS classes using Vanilla JS is to manipulate the appearance and behavior of HTML elements dynamically. By adding or removing CSS classes, you can change the style of an element, hide or show elements, animate elements, and much more. This is particularly useful in creating interactive web pages where the appearance of elements changes in response to user actions or other events.
How can I add multiple classes using classList.add()?
The classList.add() method allows you to add multiple classes to an element. You simply need to pass the class names as separate arguments. Hereās an example:
element.classList.add("class1", "class2", "class3");
This will add class1, class2, and class3 to the element.
Can I remove a class that does not exist on an element?
Yes, you can. The classList.remove() method will not throw an error if you try to remove a class that does not exist on an element. It will simply do nothing.
How can I check if an element has a specific class?
You can use the classList.contains() method to check if an element has a specific class. This method returns a boolean value ā true if the class exists, and false if it doesnāt. Hereās an example:
if (element.classList.contains("myClass")) {
// do something
}
Can I add or remove classes to/from multiple elements at once?
Yes, you can. You would need to select all the elements you want to manipulate, loop through them, and add or remove the class for each one. Hereās an example using the querySelectorAll() method to select multiple elements and a forEach loop to add a class to each one:
document.querySelectorAll(".myElements").forEach(function(element) {
element.classList.add("myClass");
});
How can I toggle a class on an element?
The classList.toggle() method allows you to toggle a class on an element. If the element already has the class, it will be removed. If it doesnāt have the class, it will be added. Hereās an example:
element.classList.toggle("myClass");
What is the difference between className and classList?
className is a property that gets or sets the class attribute of an element as a string. classList, on the other hand, is a read-only property that returns a live DOMTokenList collection of the class attributes of the element, providing methods to manipulate classes.
Can I use classList with SVG elements?
Yes, you can. The classList property is applicable to SVG elements as well, allowing you to add, remove, and toggle classes on SVG elements just like on HTML elements.
Is classList supported in all browsers?
The classList property is widely supported in all modern browsers. However, it is not supported in Internet Explorer 9 and earlier versions.
Can I chain classList methods?
Yes, you can. The classList methods return the classList object, allowing you to chain methods. Hereās an example:
element.classList.remove("oldClass").add("newClass");
This will remove oldClass and add newClass in a single line of code.
Yaphi Berhanu
Yaphi Berhanu is a web developer who loves helping people boost their coding skills. He writes tips and tricks at
http://simplestepscode.com
. In his completely unbiased opinion, he suggests checking it out. |
| Markdown | 
[Premium](https://www.sitepoint.com/premium/pricing/?ref_source=sitepoint&ref_medium=topnav)[Library](https://www.sitepoint.com/premium/library/)[Community](https://www.sitepoint.com/community/)[Save on SaaS](https://www.sitepoint.com/premium/save-on-saas/)[Jobs](https://jobs.sitepoint.com/)
Tools
Tutorials
[Blog](https://www.sitepoint.com/blog/)
Cancel
[Login](https://www.sitepoint.com/premium/sign-in/)
[Start Free Trial](https://www.sitepoint.com/premium/pricing/?ref_source=sitepoint&ref_medium=topnav)
[Premium](https://www.sitepoint.com/premium/pricing/?ref_source=sitepoint&ref_medium=topnav)
[Library](https://www.sitepoint.com/premium/library/)
[Community](https://www.sitepoint.com/community/)
[Save on SaaS](https://www.sitepoint.com/premium/save-on-saas/)
[Developer Jobs](https://jobs.sitepoint.com/)
Tutorials
Tools
Blog
[Login](https://www.sitepoint.com/premium/sign-in/)
[Start Free Trial](https://www.sitepoint.com/premium/pricing/?ref_source=sitepoint&ref_medium=topnav)
[](https://clawpilot.ai/openclaw-on-slack?utm_source=sitepoint&utm_medium=hellobar)
Table of Contents
- [Key Takeaways](https://www.sitepoint.com/add-remove-css-class-vanilla-js/#h-key-takeaways)
- [Modifying Classes the Compatible Way](https://www.sitepoint.com/add-remove-css-class-vanilla-js/#h-modifying-classes-the-compatible-way)
- [Modifying Classes the Modern Way](https://www.sitepoint.com/add-remove-css-class-vanilla-js/#h-modifying-classes-the-modern-way)
- [Conclusion](https://www.sitepoint.com/add-remove-css-class-vanilla-js/#h-conclusion)
- [Frequently Asked Questions (FAQs) on Adding and Removing CSS Classes with Vanilla JS](https://www.sitepoint.com/add-remove-css-class-vanilla-js/#h-frequently-asked-questions-faqs-on-adding-and-removing-css-classes-with-vanilla-js)
- [Blog](https://www.sitepoint.com/blog/)/
- [JavaScript](https://www.sitepoint.com/javascript/)/
- [Quick Tip: Add or Remove a CSS Class with Vanilla JavaScript](https://www.sitepoint.com/add-remove-css-class-vanilla-js/)
Table of Contents
- [Key Takeaways](https://www.sitepoint.com/add-remove-css-class-vanilla-js/#h-key-takeaways)
- [Modifying Classes the Compatible Way](https://www.sitepoint.com/add-remove-css-class-vanilla-js/#h-modifying-classes-the-compatible-way)
- [Modifying Classes the Modern Way](https://www.sitepoint.com/add-remove-css-class-vanilla-js/#h-modifying-classes-the-modern-way)
- [Conclusion](https://www.sitepoint.com/add-remove-css-class-vanilla-js/#h-conclusion)
- [Frequently Asked Questions (FAQs) on Adding and Removing CSS Classes with Vanilla JS](https://www.sitepoint.com/add-remove-css-class-vanilla-js/#h-frequently-asked-questions-faqs-on-adding-and-removing-css-classes-with-vanilla-js)
# Quick Tip: Add or Remove a CSS Class with Vanilla JavaScript
[](https://www.sitepoint.com/author/yberhanu/)
[Yaphi Berhanu](https://www.sitepoint.com/author/yberhanu/)
Published in
[JavaScript](https://www.sitepoint.com/javascript/)Ā·[Vanilla JavaScript](https://www.sitepoint.com/javascript/vanilla-javascript/)Ā·
September 28, 2016
Ā·Updated:
November 7, 2024
Share this article

SitePoint Premium
**Stay Relevant and Grow Your Career in Tech**
- Premium Results
- Publish articles on SitePoint
- Daily curated jobs
- Learning Paths
- Discounts to dev tools
[Start Free Trial](https://www.sitepoint.com/premium/pricing/)
7 Day Free Trial. Cancel Anytime.
## Key Takeaways
- Adding or removing CSS classes with JavaScript can be useful to alter page elements in response to user actions, such as showing or hiding menus, highlighting form errors, or animating elements.
- The JavaScript properties āclassNameā and āclassListā can be used to manipulate classes; āclassNameā is more widely compatible, while āclassListā is more modern and convenient.
- Functions can be created to add or remove classes from elements using either the āclassNameā or āclassListā properties. These functions can take in a string selector or the elements themselves, loop through the elements, and add or remove the specified class.
- The classList property, supported by browsers from IE10 and up, offers a range of methods to manipulate classes, including āaddā, āremoveā, and ātoggleā. This property simplifies the process of adding or removing classes compared to the āclassNameā property.
**Sometimes you need to add or remove a CSS class with JavaScript, and you donāt want to include an entire library like jQuery to do it.**
This is useful in situations when you want your page elements to change in response to user actions.
Example uses include:
- Showing or hiding a menu
- Highlighting a form error
- Showing a dialog box
- Showing different content in response to a selection
- Animating an element in response to a click
There are two JavaScript properties that let you work with classes: `className` and `classList`. The former is [widely compatible](https://developer.mozilla.org/en-US/docs/Web/API/Element/className#Browser_compatibility), while the latter is [more modern](https://developer.mozilla.org/en-US/docs/Web/API/Element/className#Browser_compatibility) and convenient. If you donāt need to support IE 8 and 9, you can skip `className`.
Weāll start with the compatible version first.
> Note: This tutorial assumes some familiarity with JavaScript concepts like functions and variables.
## Modifying Classes the Compatible Way
The JavaScript `className` property lets you access the `class` attribute of an HTML element. Some string manipulation will let us add and remove classes.
Weāll access HTML elements using [`querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll), which is compatible with browsers from IE8 and up.
### Add a Class
To add a class, weāll write a function that takes in the elements we want to change and adds a specified class to all of them.
```
function addClass(elements, myClass) {
// if there are no elements, we're done
if (!elements) { return; }
// if we have a selector, get the chosen elements
if (typeof(elements) === 'string') {
elements = document.querySelectorAll(elements);
}
// if we have a single DOM element, make it an array to simplify behavior
else if (elements.tagName) { elements=[elements]; }
// add class to all chosen elements
for (var i=0; i<elements.length; i++) {
// if class is not already found
if ( (' '+elements[i].className+' ').indexOf(' '+myClass+' ') < 0 ) {
// add class
elements[i].className += ' ' + myClass;
}
}
}
```
Youāll see how the function works soon, but to watch the function in action, feel free to use this CSS:
```
.red {
background: red;
}
.highlight {
background: gold;
}
```
ā¦and this HTML:
```
<div id="iddiv" class="highlight">ID div</div>
<div class="classdiv">Class div</div>
<div class="classdiv">Class div</div>
<div class="classdiv">Class div</div>
```
Here are some usage examples of the function itself:
```
addClass('#iddiv','highlight');
addClass('.classdiv','highlight');
addClass(document.getElementById('iddiv'),'highlight');
addClass(document.querySelector('.classdiv'),'highlight');
addClass(document.querySelectorAll('.classdiv'),'highlight');
```
Notice that you can identify the HTML elements you want to change through a selector or you can directly pass in the elements themselves.
### How Our addClass Function Works
Our `addClass` function first takes two parameters: the HTML elements we want to modify and the class we want to add. Our goal is to loop through each HTML element, make sure the class is not already there, and then add the class.
First, if the list of elements is empty, our function has nothing left to do, so we can get out early.
```
// if there are no elements, we're done
if (!elements) { return; }
```
Next, if weāve chosen to identify our HTML elements through a selector such as `#iddiv` or `.classdiv`, then we can use `querySelectorAll()` to grab all of our desired elements.
```
// if we have a selector, get the chosen elements
if (typeof(elements) === 'string') {
elements = document.querySelectorAll(elements);
}
```
However, if DOM elements are fed into the function directly, we can loop through them. If thereās a single DOM element (rather than a list), weāll make it an array so we can use the same loop and simplify our code. We can tell if thereās only one element because an element has a [tagName](https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName) property, while a list does not.
```
// if we have a single DOM element, make it an array to simplify behavior
else if (elements.tagName) { elements=[elements]; }
```
Now that we have our elements in a format we can loop over, weāll go through each one, check if the class is already there, and if not, weāll add the class.
```
// add class to all chosen elements
for (var i=0; i<elements.length; i++) {
// if class is not already found
if ( (' '+elements[i].className+' ').indexOf(' '+myClass+' ') < 0 ) {
// add class
elements[i].className += ' ' + myClass;
}
}
```
Notice weāre adding a space at the beginning and end in order to simplify the pattern weāre looking for and avoid needing a regular expression.
In any case, weāre done ā you can now add a class\!
### Remove a Class
To remove a class, we can use the following function:
```
function removeClass(elements, myClass) {
// if there are no elements, we're done
if (!elements) { return; }
// if we have a selector, get the chosen elements
if (typeof(elements) === 'string') {
elements = document.querySelectorAll(elements);
}
// if we have a single DOM element, make it an array to simplify behavior
else if (elements.tagName) { elements=[elements]; }
// create pattern to find class name
var reg = new RegExp('(^| )'+myClass+'($| )','g');
// remove class from all chosen elements
for (var i=0; i<elements.length; i++) {
elements[i].className = elements[i].className.replace(reg,' ');
}
}
```
Most of this `removeClass` function works the same way as our `addClass` function; by gathering the desired HTML elements and looping through them. The only difference is the part where the class gets removed.
Hereās the class removal in more detail:
```
// create pattern to find class name
var reg = new RegExp('(^| )'+myClass+'($| )','g');
// remove class from all chosen elements
for (var i=0; i<elements.length; i++) {
elements[i].className = elements[i].className.replace(reg,' ');
}
```
First, we create a regular expression to look for all instances of our desired class. The expression `'(^| )'+myClass+'($| )'` means the beginning or a space followed by `myClass` followed by the end or a space. The `'g'` means global match, which means find all instances of the pattern.
Using our pattern, we replace the class name with a space. That way, class names in the middle of the list will remain separated, and thereās no harm done if the removed class is on the ends.
## Modifying Classes the Modern Way
Browsers from IE10 and up support a property called [classList](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Browser_compatibility), which makes an elementās classes much easier to deal with.
In [a previous article](https://www.sitepoint.com/jquery-vs-raw-javascript-2-css3-animation/), Craig Buckler provided a list of things `classList` can do:
> The following properties are available:
>
> length ā the number of class names applied
> item(index) ā the class name at a specific index
> contains(class) ā returns true if a node has that class applied
> add(class) ā applies a new class to the node
> remove(class) ā removes a class from the node
> toggle(class) ā removes or adds a class if itās applied or not applied respectively
>
> We can use this in preference to the clunkier className property:
> ```
> document.getElementById("myelement").classList.add("myclass");
> ```
Letās use this information to create functions that add and remove classes from all elements that match a selector.
These functions will get all desired elements, loop through them, and add or remove a class to each one.
### Add Class
```
function addClass(selector, myClass) {
// get all elements that match our selector
elements = document.querySelectorAll(selector);
// add class to all chosen elements
for (var i=0; i<elements.length; i++) {
elements[i].classList.add(myClass);
}
}
// usage examples:
addClass('.class-selector', 'example-class');
addClass('#id-selector', 'example-class');
```
### Remove class
```
function removeClass(selector, myClass) {
// get all elements that match our selector
elements = document.querySelectorAll(selector);
// remove class from all chosen elements
for (var i=0; i<elements.length; i++) {
elements[i].classList.remove(myClass);
}
}
// usage examples:
removeClass('.class-selector', 'example-class');
removeClass('#id-selector', 'example-class');
```
## Conclusion
Weāve covered how to add and remove classes through `className` (the compatible way) and `classList` (the more modern way).
When you can control CSS classes through JavaScript, you unlock a lot of functionality including content display updates, animations, error messages, dialogs, menus, and more.
I hope this article has been helpful, and if you have any questions or thoughts, please feel free to share them in the comments.
## Frequently Asked Questions (FAQs) on Adding and Removing CSS Classes with Vanilla JS
### What is the purpose of adding or removing CSS classes using Vanilla JS?
The primary purpose of adding or removing CSS classes using Vanilla JS is to manipulate the appearance and behavior of HTML elements dynamically. By adding or removing CSS classes, you can change the style of an element, hide or show elements, animate elements, and much more. This is particularly useful in creating interactive web pages where the appearance of elements changes in response to user actions or other events.
### How can I add multiple classes using classList.add()?
The classList.add() method allows you to add multiple classes to an element. You simply need to pass the class names as separate arguments. Hereās an example:
`element.classList.add("class1", "class2", "class3");`
This will add class1, class2, and class3 to the element.
### Can I remove a class that does not exist on an element?
Yes, you can. The classList.remove() method will not throw an error if you try to remove a class that does not exist on an element. It will simply do nothing.
### How can I check if an element has a specific class?
You can use the classList.contains() method to check if an element has a specific class. This method returns a boolean value ā true if the class exists, and false if it doesnāt. Hereās an example:
`if (element.classList.contains("myClass")) {`
`// do something`
`}`
### Can I add or remove classes to/from multiple elements at once?
Yes, you can. You would need to select all the elements you want to manipulate, loop through them, and add or remove the class for each one. Hereās an example using the querySelectorAll() method to select multiple elements and a forEach loop to add a class to each one:
`document.querySelectorAll(".myElements").forEach(function(element) {`
`element.classList.add("myClass");`
`});`
### How can I toggle a class on an element?
The classList.toggle() method allows you to toggle a class on an element. If the element already has the class, it will be removed. If it doesnāt have the class, it will be added. Hereās an example:
`element.classList.toggle("myClass");`
### What is the difference between className and classList?
className is a property that gets or sets the class attribute of an element as a string. classList, on the other hand, is a read-only property that returns a live DOMTokenList collection of the class attributes of the element, providing methods to manipulate classes.
### Can I use classList with SVG elements?
Yes, you can. The classList property is applicable to SVG elements as well, allowing you to add, remove, and toggle classes on SVG elements just like on HTML elements.
### Is classList supported in all browsers?
The classList property is widely supported in all modern browsers. However, it is not supported in Internet Explorer 9 and earlier versions.
### Can I chain classList methods?
Yes, you can. The classList methods return the classList object, allowing you to chain methods. Hereās an example:
`element.classList.remove("oldClass").add("newClass");`
This will remove oldClass and add newClass in a single line of code.
Close
[Yaphi Berhanu](https://www.sitepoint.com/author/yberhanu/)
Yaphi Berhanu is a web developer who loves helping people boost their coding skills. He writes tips and tricks at [http://simplestepscode.com](https://simplestepscode.com/). In his completely unbiased opinion, he suggests checking it out.
[](https://clawpilot.ai/openclaw-on-slack?utm_source=sitepoint&utm_medium=sidead)
Stuff we do
[Premium](https://www.sitepoint.com/premium/library/)[Newsletters](https://www.sitepoint.com/newsletters/)[Learning paths](https://www.sitepoint.com/premium/library/paths/)[Library](https://www.sitepoint.com/premium/library/)[Forums](https://www.sitepoint.com/community/)
Contact
[Contact us](https://www.sitepoint.com/contact-us/)[FAQ](https://www.sitepoint.com/faq/)[Publish your book with us](<mailto:support@sitepoint.com?subject=I'd like to publish my book on SitePoint>)[Write an article with us](https://www.sitepoint.com/write-for-us/)[Advertise](https://www.sitepoint.com/partnerships/)
About
[Our story](https://www.sitepoint.com/about-us/)[Corporate memberships](https://www.sitepoint.com/premium-for-teams/)[Start free trial](https://www.sitepoint.com/premium/pricing/?ref_source=sitepoint&unlock=true&ref_medium=hp-footer)[Login](https://www.sitepoint.com/premium/sign-in/)
Connect
[RSS](https://www.sitepoint.com/sitepoint.rss)[Facebook](https://www.facebook.com/sitepoint)[Instagram](https://www.instagram.com/sitepointdotcom/?hl=en)[Twitter (X)](https://twitter.com/sitepointdotcom)
Subscribe to our newsletter
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Ā© 2000 ā 2026 SitePoint Pty. Ltd.
[Back to top]()
This site is protected by reCAPTCHA and the Google [Privacy Policy](https://policies.google.com/privacy) and [Terms of Service](https://policies.google.com/terms) apply.
[Privacy Policy](https://www.sitepoint.com/privacy-policy/)[Terms of Service](https://www.sitepoint.com/legals/) |
| Readable Markdown | [](https://www.sitepoint.com/author/yberhanu/)
[Yaphi Berhanu](https://www.sitepoint.com/author/yberhanu/)
Published in
September 28, 2016
Ā·Updated: November 7, 2024
Share this article

## Key Takeaways
- Adding or removing CSS classes with JavaScript can be useful to alter page elements in response to user actions, such as showing or hiding menus, highlighting form errors, or animating elements.
- The JavaScript properties āclassNameā and āclassListā can be used to manipulate classes; āclassNameā is more widely compatible, while āclassListā is more modern and convenient.
- Functions can be created to add or remove classes from elements using either the āclassNameā or āclassListā properties. These functions can take in a string selector or the elements themselves, loop through the elements, and add or remove the specified class.
- The classList property, supported by browsers from IE10 and up, offers a range of methods to manipulate classes, including āaddā, āremoveā, and ātoggleā. This property simplifies the process of adding or removing classes compared to the āclassNameā property.
**Sometimes you need to add or remove a CSS class with JavaScript, and you donāt want to include an entire library like jQuery to do it.**
This is useful in situations when you want your page elements to change in response to user actions.
Example uses include:
- Showing or hiding a menu
- Highlighting a form error
- Showing a dialog box
- Showing different content in response to a selection
- Animating an element in response to a click
There are two JavaScript properties that let you work with classes: `className` and `classList`. The former is [widely compatible](https://developer.mozilla.org/en-US/docs/Web/API/Element/className#Browser_compatibility), while the latter is [more modern](https://developer.mozilla.org/en-US/docs/Web/API/Element/className#Browser_compatibility) and convenient. If you donāt need to support IE 8 and 9, you can skip `className`.
Weāll start with the compatible version first.
> Note: This tutorial assumes some familiarity with JavaScript concepts like functions and variables.
## Modifying Classes the Compatible Way
The JavaScript `className` property lets you access the `class` attribute of an HTML element. Some string manipulation will let us add and remove classes.
Weāll access HTML elements using [`querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll), which is compatible with browsers from IE8 and up.
### Add a Class
To add a class, weāll write a function that takes in the elements we want to change and adds a specified class to all of them.
```
function addClass(elements, myClass) {
// if there are no elements, we're done
if (!elements) { return; }
// if we have a selector, get the chosen elements
if (typeof(elements) === 'string') {
elements = document.querySelectorAll(elements);
}
// if we have a single DOM element, make it an array to simplify behavior
else if (elements.tagName) { elements=[elements]; }
// add class to all chosen elements
for (var i=0; i<elements.length; i++) {
// if class is not already found
if ( (' '+elements[i].className+' ').indexOf(' '+myClass+' ') < 0 ) {
// add class
elements[i].className += ' ' + myClass;
}
}
}
```
Youāll see how the function works soon, but to watch the function in action, feel free to use this CSS:
```
.red {
background: red;
}
.highlight {
background: gold;
}
```
ā¦and this HTML:
```
<div id="iddiv" class="highlight">ID div</div>
<div class="classdiv">Class div</div>
<div class="classdiv">Class div</div>
<div class="classdiv">Class div</div>
```
Here are some usage examples of the function itself:
```
addClass('#iddiv','highlight');
addClass('.classdiv','highlight');
addClass(document.getElementById('iddiv'),'highlight');
addClass(document.querySelector('.classdiv'),'highlight');
addClass(document.querySelectorAll('.classdiv'),'highlight');
```
Notice that you can identify the HTML elements you want to change through a selector or you can directly pass in the elements themselves.
### How Our addClass Function Works
Our `addClass` function first takes two parameters: the HTML elements we want to modify and the class we want to add. Our goal is to loop through each HTML element, make sure the class is not already there, and then add the class.
First, if the list of elements is empty, our function has nothing left to do, so we can get out early.
```
// if there are no elements, we're done
if (!elements) { return; }
```
Next, if weāve chosen to identify our HTML elements through a selector such as `#iddiv` or `.classdiv`, then we can use `querySelectorAll()` to grab all of our desired elements.
```
// if we have a selector, get the chosen elements
if (typeof(elements) === 'string') {
elements = document.querySelectorAll(elements);
}
```
However, if DOM elements are fed into the function directly, we can loop through them. If thereās a single DOM element (rather than a list), weāll make it an array so we can use the same loop and simplify our code. We can tell if thereās only one element because an element has a [tagName](https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName) property, while a list does not.
```
// if we have a single DOM element, make it an array to simplify behavior
else if (elements.tagName) { elements=[elements]; }
```
Now that we have our elements in a format we can loop over, weāll go through each one, check if the class is already there, and if not, weāll add the class.
```
// add class to all chosen elements
for (var i=0; i<elements.length; i++) {
// if class is not already found
if ( (' '+elements[i].className+' ').indexOf(' '+myClass+' ') < 0 ) {
// add class
elements[i].className += ' ' + myClass;
}
}
```
Notice weāre adding a space at the beginning and end in order to simplify the pattern weāre looking for and avoid needing a regular expression.
In any case, weāre done ā you can now add a class\!
### Remove a Class
To remove a class, we can use the following function:
```
function removeClass(elements, myClass) {
// if there are no elements, we're done
if (!elements) { return; }
// if we have a selector, get the chosen elements
if (typeof(elements) === 'string') {
elements = document.querySelectorAll(elements);
}
// if we have a single DOM element, make it an array to simplify behavior
else if (elements.tagName) { elements=[elements]; }
// create pattern to find class name
var reg = new RegExp('(^| )'+myClass+'($| )','g');
// remove class from all chosen elements
for (var i=0; i<elements.length; i++) {
elements[i].className = elements[i].className.replace(reg,' ');
}
}
```
Most of this `removeClass` function works the same way as our `addClass` function; by gathering the desired HTML elements and looping through them. The only difference is the part where the class gets removed.
Hereās the class removal in more detail:
```
// create pattern to find class name
var reg = new RegExp('(^| )'+myClass+'($| )','g');
// remove class from all chosen elements
for (var i=0; i<elements.length; i++) {
elements[i].className = elements[i].className.replace(reg,' ');
}
```
First, we create a regular expression to look for all instances of our desired class. The expression `'(^| )'+myClass+'($| )'` means the beginning or a space followed by `myClass` followed by the end or a space. The `'g'` means global match, which means find all instances of the pattern.
Using our pattern, we replace the class name with a space. That way, class names in the middle of the list will remain separated, and thereās no harm done if the removed class is on the ends.
## Modifying Classes the Modern Way
Browsers from IE10 and up support a property called [classList](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Browser_compatibility), which makes an elementās classes much easier to deal with.
In [a previous article](https://www.sitepoint.com/jquery-vs-raw-javascript-2-css3-animation/), Craig Buckler provided a list of things `classList` can do:
> The following properties are available:
>
> length ā the number of class names applied
> item(index) ā the class name at a specific index
> contains(class) ā returns true if a node has that class applied
> add(class) ā applies a new class to the node
> remove(class) ā removes a class from the node
> toggle(class) ā removes or adds a class if itās applied or not applied respectively
>
> We can use this in preference to the clunkier className property:
> ```
> document.getElementById("myelement").classList.add("myclass");
> ```
Letās use this information to create functions that add and remove classes from all elements that match a selector.
These functions will get all desired elements, loop through them, and add or remove a class to each one.
### Add Class
```
function addClass(selector, myClass) {
// get all elements that match our selector
elements = document.querySelectorAll(selector);
// add class to all chosen elements
for (var i=0; i<elements.length; i++) {
elements[i].classList.add(myClass);
}
}
// usage examples:
addClass('.class-selector', 'example-class');
addClass('#id-selector', 'example-class');
```
### Remove class
```
function removeClass(selector, myClass) {
// get all elements that match our selector
elements = document.querySelectorAll(selector);
// remove class from all chosen elements
for (var i=0; i<elements.length; i++) {
elements[i].classList.remove(myClass);
}
}
// usage examples:
removeClass('.class-selector', 'example-class');
removeClass('#id-selector', 'example-class');
```
## Conclusion
Weāve covered how to add and remove classes through `className` (the compatible way) and `classList` (the more modern way).
When you can control CSS classes through JavaScript, you unlock a lot of functionality including content display updates, animations, error messages, dialogs, menus, and more.
I hope this article has been helpful, and if you have any questions or thoughts, please feel free to share them in the comments.
## Frequently Asked Questions (FAQs) on Adding and Removing CSS Classes with Vanilla JS
### What is the purpose of adding or removing CSS classes using Vanilla JS?
The primary purpose of adding or removing CSS classes using Vanilla JS is to manipulate the appearance and behavior of HTML elements dynamically. By adding or removing CSS classes, you can change the style of an element, hide or show elements, animate elements, and much more. This is particularly useful in creating interactive web pages where the appearance of elements changes in response to user actions or other events.
### How can I add multiple classes using classList.add()?
The classList.add() method allows you to add multiple classes to an element. You simply need to pass the class names as separate arguments. Hereās an example:
`element.classList.add("class1", "class2", "class3");`
This will add class1, class2, and class3 to the element.
### Can I remove a class that does not exist on an element?
Yes, you can. The classList.remove() method will not throw an error if you try to remove a class that does not exist on an element. It will simply do nothing.
### How can I check if an element has a specific class?
You can use the classList.contains() method to check if an element has a specific class. This method returns a boolean value ā true if the class exists, and false if it doesnāt. Hereās an example:
`if (element.classList.contains("myClass")) {`
`// do something`
`}`
### Can I add or remove classes to/from multiple elements at once?
Yes, you can. You would need to select all the elements you want to manipulate, loop through them, and add or remove the class for each one. Hereās an example using the querySelectorAll() method to select multiple elements and a forEach loop to add a class to each one:
`document.querySelectorAll(".myElements").forEach(function(element) {`
`element.classList.add("myClass");`
`});`
### How can I toggle a class on an element?
The classList.toggle() method allows you to toggle a class on an element. If the element already has the class, it will be removed. If it doesnāt have the class, it will be added. Hereās an example:
`element.classList.toggle("myClass");`
### What is the difference between className and classList?
className is a property that gets or sets the class attribute of an element as a string. classList, on the other hand, is a read-only property that returns a live DOMTokenList collection of the class attributes of the element, providing methods to manipulate classes.
### Can I use classList with SVG elements?
Yes, you can. The classList property is applicable to SVG elements as well, allowing you to add, remove, and toggle classes on SVG elements just like on HTML elements.
### Is classList supported in all browsers?
The classList property is widely supported in all modern browsers. However, it is not supported in Internet Explorer 9 and earlier versions.
### Can I chain classList methods?
Yes, you can. The classList methods return the classList object, allowing you to chain methods. Hereās an example:
`element.classList.remove("oldClass").add("newClass");`
This will remove oldClass and add newClass in a single line of code.
[Yaphi Berhanu](https://www.sitepoint.com/author/yberhanu/)
Yaphi Berhanu is a web developer who loves helping people boost their coding skills. He writes tips and tricks at [http://simplestepscode.com](https://simplestepscode.com/). In his completely unbiased opinion, he suggests checking it out. |
| Shard | 163 (laksa) |
| Root Hash | 18207014666102764963 |
| Unparsed URL | com,sitepoint!www,/add-remove-css-class-vanilla-js/ s443 |