Hello! Welcome back to your front-end development course.
In the last lesson, we saw how to change an element's attributes, like an image's src or a button's disabled state. This gave us direct control over an element's fundamental properties and behavior.
Today, we'll focus on one of the most powerful and common ways to change an element's appearance: manipulating its CSS classes. This lesson directly addresses the learning outcome: Add, remove, and toggle CSS classes on elements using classList methods.
For a designer, this is a pivotal concept. The different states you create for a component in Figma—like 'active', 'error', 'selected', or 'expanded'—are almost always implemented in code by adding or removing CSS classes. This lesson is the bridge that connects your JavaScript logic (user actions) to your CSS styles (visual states).
1. The Old Way vs. The New Way: className vs. classList
Before we dive into the modern approach, it's helpful to see what it replaced. In the past, developers had to manipulate a single string containing all of an element's classes. This was clumsy and prone to errors.
The modern classList property, on the other hand, provides a set of simple, clear methods to manage classes. The following video does an excellent job of demonstrating the difference and introducing the core classList methods we'll be using today.
The Difference Between className & classList in JavaScript
This video from the dcode channel, "The Difference Between className & classList in JavaScript", clearly illustrates why classList is the preferred method for managing CSS classes.
Please watch the following segments: className demonstration (01:10 - 03:45): Notice how adding and removing classes requires manual string manipulation, including adding spaces. This highlights the problems classList solves. Introducing classList (03:45 - 04:48): See how classList is an object, not just a string. Adding and removing classes (04:48 - 06:00): Observe the simplicity of the .add() and .remove() methods. Toggling classes (06:47 - 07:27): Pay close attention to the .toggle() method, as it's extremely useful for interactive UI elements.
As you saw, classList saves you from messy string operations and makes your code much more readable and reliable.
2. Understanding the classList API
The classList property gives you access to a DOMTokenList, which is essentially a list of the element's classes. While the list itself is read-only, it comes with methods to modify its contents.
This article from Handoff.design is written with a designer's perspective in mind and explains the importance of class manipulation in creating modern, interactive user interfaces.
Manipulating CSS Classes with JavaScript - Handoff.design
The article "Manipulating CSS Classes with JavaScript" explains the role of class manipulation in bridging application logic with visual presentation. It's a great conceptual overview.
Please read the sections: Using the classList API Adding CSS Classes Removing CSS Classes Toggling CSS Classes Focus on how the article frames these methods as tools for building dynamic and responsive interfaces, connecting directly to the work you do in design.
For a more technical and concise reference, the MDN documentation is the industry standard. It provides clear examples of the syntax for each method.
Element: classList property - Web APIs | MDN
The MDN Web Docs for Element: classList property is the definitive technical guide. It's a valuable resource to bookmark for future reference.
Read the Value section and review the code in the Examples section. This will solidify your understanding of the add(), remove(), and toggle() methods.
3. The Core classList Methods
Let's summarize the three key methods you'll use constantly:
-
element.classList.add('className')- Adds the specified class to the element.
- You can add multiple classes at once:
element.classList.add('class1', 'class2'). - It will not add a class if the element already has it, preventing duplicates.
-
element.classList.remove('className')- Removes the specified class from the element.
- You can remove multiple classes at once.
- It doesn't produce an error if the class isn't present, which makes your code safer.
-
element.classList.toggle('className')- This is the most powerful method for interactive UI.
- If the class exists, it removes it.
- If the class does not exist, it adds it.
- Perfect for things like accordions, modals, navigation menus, and dark/light mode switches.
4. Your Turn: Building an Interactive Accordion
Now, let's apply these concepts to build a common UI component: an accordion. This is a perfect use case for classList.toggle().
Here is the starting HTML and CSS. The CSS hides the .accordion-content by default and defines an .active class that will make it visible. Your job is to write the JavaScript to apply this .active class when a user clicks on a question.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Accordion Example</title>
<style>
body {
font-family: sans-serif;
background-color: #f4f4f9;
padding: 2rem;
}
.accordion {
max-width: 600px;
margin: 0 auto;
border: 1px solid #ddd;
border-radius: 8px;
overflow: hidden;
}
.accordion-item {
border-bottom: 1px solid #ddd;
}
.accordion-item:last-child {
border-bottom: none;
}
.accordion-header {
background-color: #fff;
padding: 15px 20px;
cursor: pointer;
font-weight: bold;
display: flex;
justify-content: space-between;
align-items: center;
}
.accordion-header::after {
content: '+';
font-size: 1.5rem;
color: #888;
transition: transform 0.2s;
}
.accordion-content {
/* Hide the content by default */
max-height: 0;
overflow: hidden;
padding: 0 20px;
background-color: #fff;
transition: max-height 0.3s ease-out, padding 0.3s ease-out;
}
/* Style for the active state */
.accordion-item.active .accordion-content {
max-height: 200px; /* Set to a value larger than content */
padding: 15px 20px;
}
.accordion-item.active .accordion-header::after {
transform: rotate(45deg);
}
</style>
</head>
<body>
<h1>Frequently Asked Questions</h1>
<div class="accordion">
<div class="accordion-item">
<div class="accordion-header">What is a UX Designer?</div>
<div class="accordion-content">
<p>A UX (User Experience) Designer is focused on the overall feel of the experience, ensuring the product is logical, easy to use, and meets the user's needs.</p>
</div>
</div>
<div class="accordion-item">
<div class="accordion-header">What is a UI Designer?</div>
<div class="accordion-content">
<p>A UI (User Interface) Designer is focused on the visual aspects of a product's interface. They work on typography, color palettes, buttons, and the layout of every screen.</p>
</div>
</div>
<div class="accordion-item">
<div class="accordion-header">How do they work together?</div>
<div class="accordion-content">
<p>UX and UI designers work closely. The UX designer defines the user flow and wireframes, and the UI designer then creates the high-fidelity visual design based on that structure.</p>
</div>
</div>
</div>
<script>
// Select all the accordion headers
const accordionHeaders = document.querySelectorAll('.accordion-header');
// Loop through each header
accordionHeaders.forEach(header => {
// Add a click event listener to it
header.addEventListener('click', () => {
// Task: Toggle the 'active' class on the PARENT '.accordion-item'
// Hint: An element's parent can be accessed with `element.parentElement`
// Your code goes here!
});
});
</script>
</body>
</html>
Your Task:
- Copy the code above into a new HTML file.
- Inside the
addEventListenerfunction, find the line that says// Your code goes here!. - Write one line of JavaScript to select the parent element of the clicked
header(which is the.accordion-itemdiv) andtoggletheactiveclass on it.
When you're done, clicking on a question should smoothly reveal the answer, and clicking it again should hide it.
Click here to see the solution
// Select all the accordion headers
const accordionHeaders = document.querySelectorAll('.accordion-header');
// Loop through each header
accordionHeaders.forEach(header => {
// Add a click event listener to it
header.addEventListener('click', () => {
// Task: Toggle the 'active' class on the PARENT '.accordion-item'
// Hint: An element's parent can be accessed with `element.parentElement`
header.parentElement.classList.toggle('active');
});
});
Conclusion
Great job! You've just implemented a fully functional UI component that is used all over the web. You now have the primary toolset for making your designs come to life with dynamic styling.
Key Takeaways:
- Manipulating CSS classes is the standard way to change an element's style and state in response to user interaction.
- The
classListproperty is the modern, safe, and readable API for this task. - The core methods are
add(),remove(), andtoggle(). classList.toggle()is especially powerful for creating interactive elements like menus, modals, and accordions.
In our next lesson, we'll move from modifying existing elements to creating them from scratch. You will learn how to create new elements and append them to the DOM using createElement and appendChild, allowing you to build dynamic lists, add notifications, and much more.
Can't find a good explanation? Sign up and we'll make it for you
Sign up