In this article, we will explore the JavaScript classList
property. This property provides a powerful way to manipulate an element’s CSS classes in your web applications. We will cover how to add, remove, toggle, and check for classes, as well as provide practical examples to help you understand its usage.
What is classList
?
The classList
property is a built-in JavaScript object that represents the list of CSS classes applied to an HTML element. It provides a convenient way to manage these classes without directly manipulating the class
attribute as a string.
Why Use classList
?
Using classList
is more efficient and less error-prone than manually splitting and joining the class
attribute string. It also provides a cleaner and more readable syntax for class manipulation.
Basic Usage
To use classList
, you first need to access an HTML element using JavaScript. You can do this using methods like document.getElementById()
or document.querySelector()
. Once you have the element, you can access its classList
property.
Example: Accessing classList
<div id="myElement" class="active visible"></div>
<script>
// Get the element
const element = document.getElementById('myElement');
// Access classList
const classes = element.classList;
console.log(classes); // Outputs: DOMTokenList ['active', 'visible']
</script>
Common Methods
The classList
object provides several methods to manipulate classes. The most commonly used methods are:
1. add()
– Adding a Class
The add()
method adds a new class to the element. If the class already exists, it will not be duplicated.
Example: Adding a Class
<button id="myButton">Click Me</button>
<script>
const button = document.getElementById('myButton');
// Add a class
button.classList.add('active');
console.log(button.classList); // Outputs: DOMTokenList ['active']
</script>
2. remove()
– Removing a Class
The remove()
method removes a class from the element. If the class does not exist, it will do nothing.
Example: Removing a Class
<button id="myButton" class="active">Click Me</button>
<script>
const button = document.getElementById('myButton');
// Remove the class
button.classList.remove('active');
console.log(button.classList); // Outputs: DOMTokenList []
</script>
3. toggle()
– Toggling a Class
The toggle()
method adds the class if it does not exist, or removes it if it does. This is useful for creating toggle effects, such as showing/hiding elements or activating/deactivating features.
Example: Toggling a Class
<button id="myButton">Toggle Class</button>
<script>
const button = document.getElementById('myButton');
// Toggle the class
button.classList.toggle('active');
// Click the button to toggle the class
button.addEventListener('click', function() {
this.classList.toggle('active');
});
</script>
4. contains()
– Checking for a Class
The contains()
method checks if a class exists in the element’s class list. It returns true
if the class is present, and false
otherwise.
Example: Checking for a Class
<div id="myElement" class="active visible"></div>
<script>
const element = document.getElementById('myElement');
// Check if 'active' class exists
console.log(element.classList.contains('active')); // Outputs: true
// Check if 'hidden' class exists
console.log(element.classList.contains('hidden')); // Outputs: false
</script>
Practical Examples
Example 1: Toggle Theme
In this example, we will create a button that toggles between a light and dark theme by adding and removing classes.
<body>
<button id="themeToggle">Toggle Theme</button>
<style>
.dark-theme {
background-color: #333;
color: #fff;
}
</style>
<script>
const body = document.body;
const themeToggle = document.getElementById('themeToggle');
themeToggle.addEventListener('click', function() {
body.classList.toggle('dark-theme');
});
</script>
</body>
Example 2: Show/Hide Content
In this example, we will create tabs that show and hide content based on class toggling.
<div class="tab-container">
<button class="tab-button active" data-tab="tab1">Tab 1</button>
<button class="tab-button" data-tab="tab2">Tab 2</button>
<div id="tab1" class="tab-content active">
<h2>Content for Tab 1</h2>
</div>
<div id="tab2" class="tab-content">
<h2>Content for Tab 2</h2>
</div>
</div>
<style>
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
</style>
<script>
const tabButtons = document.querySelectorAll('.tab-button');
const tabContents = document.querySelectorAll('.tab-content');
tabButtons.forEach(button => {
button.addEventListener('click', function() {
// Remove 'active' class from all buttons and contents
tabButtons.forEach(btn => btn.classList.remove('active'));
tabContents.forEach(content => content.classList.remove('active'));
// Add 'active' class to clicked button and corresponding content
this.classList.add('active');
const tabId = this.dataset.tab;
document.getElementById(tabId).classList.add('active');
});
});
</script>
Frequently Asked Questions
1. Can I add multiple classes at once?
No, the classList.add()
method only accepts one class at a time. However, you can chain multiple add()
calls to add multiple classes.
// Add multiple classes
element.classList.add('class1');
element.classList.add('class2');
2. Can I remove multiple classes at once?
No, the classList.remove()
method also only accepts one class at a time. You can chain multiple remove()
calls to remove multiple classes.
// Remove multiple classes
element.classList.remove('class1');
element.classList.remove('class2');
3. What if a class has spaces in its name?
Class names cannot contain spaces. If you need to apply multiple classes, you should use separate class names separated by spaces in the class
attribute, and manage them individually using classList
.
4. Is classList
supported in all browsers?
Yes, the classList
API is supported in all modern browsers, including Internet Explorer 10 and later.
5. Can I use classList
with dynamically created elements?
Yes, as long as you have a reference to the element, you can access its classList
property and manipulate its classes.
Conclusion
The classList
property is a powerful and convenient tool for managing an element’s CSS classes in JavaScript. By using its methods like add()
, remove()
, toggle()
, and contains()
, you can easily manipulate classes without directly dealing with the class
attribute as a string. This makes your code cleaner, more readable, and less error-prone.
We hope this article has given you a solid understanding of how to use classList
in your web development projects. Experiment with the examples provided, and don’t hesitate to explore further to unlock more possibilities!