1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
Greetings! 😀 In this blogpost , we will see how to dynamically manipulate classes on the `<body>` (or any other) HTML element using JavaScript. We’ll also see the safety and efficiency of classList methods, especially when dealing with multiple classes and potentially missing class names. Let’s dive in!
We’ll cover examples by modifiying classes on using <body>
element, but you can apply same on any other HTML elements.
const bodyElement = document.body;
Now that we have our target in sight, let’s see the methods for adding, removing, and toggling classes on it.
First up, the direct class assignment. While it may seem straightforward, appending classes directly to className might be less elegant when dealing with multiple classes:
document.body.className += ' dark-mode';
Here, a space is crucial to separate the added class from existing ones. However, it lacks the precision and safety that classList methods offer.
The classList.add() method proves to be more elegant and safer, especially when dealing with multiple classes:
document.body.classList.add('dark-mode', 'large-font');
This method accepts multiple classes as arguments, ensuring a clean and organized way to handle diverse styling scenarios.
When it’s time to bid adieu to a class, classList.remove() provides a precise solution:
document.body.classList.remove('dark-mode');
This method ensures that the specified class is gracefully removed, avoiding unintentional removal of other classes that might share similar names.
The classList.toggle() method offers flexibility, especially when dealing with dynamic user interactions:
document.body.classList.toggle('dark-mode');
This method excels in scenarios where you want to toggle a class on and off, catering to features like light/dark mode switches.
Now, let’s address the safety concerns when dealing with multiple classes and potential missing class names.
Consider a scenario where you want to add multiple classes, but some might already exist. Using classList.add() ensures each class is added only if it’s not already present, preventing unintended duplication:
document.body.classList.add('dark-mode', 'large-font');
If you attempt to remove a class that doesn’t exist, classList.remove()
gracefully handles it without throwing errors. This safety net minimizes the risk of runtime errors.
document.body.classList.remove('non-existent-class');
In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.
Create a button that dynamically toggles the presence of the “highlight” class on the element. Write code for such a JavaScript function (referred
toggleHighlight()
in below HTML ) to achieve this dynamic behavior. You can place it inscripts.js
file.
<!-- HTML -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Dynamic Class Toggling</title>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<button onclick="toggleHighlight()">Toggle Highlight</button>
<script src="script.js"></script>
</body>
</html>
Please attempt before seeing the Answer:
// JavaScript (script.js)
function toggleHighlight() {
document.body.classList.toggle('highlight');
}
In conclusion, dynamically manipulating classes on the element is not only about style but also about safety and efficiency. The classList methods provide a robust toolkit for adding, removing, and toggling classes, ensuring your web applications stay stylish and error-free.
May your web pages are always updated with latest styles💻✨.
Keep coding, in style!
Feel free to reach out!