JavaScript: Easily Add Classes to Elements
Adding a class to an HTML element using JavaScript can be useful for dynamically applying styles or adding functionality to elements on your web page. This process involves selecting the element you want to modify and then using JavaScript methods to add the desired class. This article explores different methods to achieve this.
01. Using the classList.add()
Method:
The classList.add()
method is the most straightforward way to add a class to an element. It allows you to add one or more classes to the element's classList
.
// Select the element
let element = document.getElementById("myElement");
// Add a class to the element
element.classList.add("new-class");
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add Class Example</title>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<p id="target">This is a simple paragraph.</p>
<button id="btn">Add Class</button>
<script>
// Get the button and paragraph elements
const button = document.getElementById('btn');
const paragraph = document.getElementById('target');
// Add an event listener to the button
button.addEventListener('click', () => {
// Add the 'highlight' class to the paragraph
paragraph.classList.add('highlight');
});
</script>
</body>
</html>
In this example, we select an element with the ID myElement
and add the class new-class
to it. If the class already exists, it won't be added again.
02. Using the className
Property:
The className
property can be used to add a class by setting it directly. This approach replaces the entire class list with the new value, so you need to append the new class to the existing ones.
// Select the element
let element = document.getElementById("myElement");
// Add a class to the element by modifying className
element.className += " new-class";
Here, we append the new-class
to the existing class list. Ensure there is a leading space before the new class to separate it from existing classes.
03. Using the classList.toggle()
Method:
The classList.toggle()
method adds a class if it does not exist and removes it if it does. This method is useful for toggling classes on and off based on certain conditions.
// Select the element
let element = document.getElementById("myElement");
// Toggle a class on the element
element.classList.toggle("toggle-class");
In this example, the toggle()
method will add toggle-class
if it is not present or remove it if it is already there.
Support Our Work: BuyMeACoffee
Originally published at https://www.rustcodeweb.com on August 15, 2024.