Change Class with JavaScript Summary
JavaScript can add or remove a CSS class after a page loads. This lets a webpage change an element’s appearance by applying styles that are already written in the CSS.
Changing a class keeps the design in the CSS instead of putting individual style changes in the JavaScript. JavaScript decides when the class is added, and CSS decides what the class looks like.
How to Add a Class with JavaScript
First, the HTML needs an element for JavaScript to find. This paragraph has an ID attribute named message.
<p id="message">This message is important.</p>
The CSS class describes how the paragraph should look when it becomes active:
.active {
background: #5e51ce;
color: white;
}
JavaScript can add that class with one line:
document.querySelector('#message').classList.add('active');
When the code runs, the paragraph receives class="active", so the browser applies the background and text colors from the CSS.
Find the HTML Element
The first part of the line finds the element that JavaScript will change:
document.querySelector('#message')
document means the current webpage. querySelector() searches that page using a CSS selector. The #message selector finds the element with id="message".
Add the CSS Class
The second part adds the class:
.classList.add('active');
classList represents the classes on the selected element. add('active') adds the class named active. The class name goes inside quotation marks without the period used in a CSS selector.
JavaScript can also remove a class with classList.remove() or switch it on and off with classList.toggle(). These methods work with classes already defined in the CSS.
Why Change a Class?
A class can apply several CSS styles at once. This is useful when an element needs a complete visual state rather than one small style change.
- Highlight a selected option.
- Mark a form field as correct or incorrect.
- Open or close a navigation menu.
- Change a card into an active state.
Using a class also keeps the same styles available to HTML, CSS, and JavaScript. If the design changes later, you can update the CSS without rewriting the JavaScript.
Try a Different Class
In the sandbox, change the background or text color inside the .active CSS rule. Then select Update Code to see the new appearance.
You can also rename active, but the name must match in both the CSS and JavaScript. Change one name at a time and check that both places use the same spelling.