🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Table of Contents
- Using
classList.add() - Adding Multiple Classes
- Checking if an Element Has a Class Before Adding
- Using
classNameProperty (Legacy Method) - Conclusion
1. Using classList.add()
The classList.add() method is the most straightforward and modern way to add a class to an element in JavaScript. This method ensures that the class is added only once, even if it’s already present.
Example:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.highlight {
color: white;
background-color: red;
padding: 10px;
}
</style>
<title>Add Class Example</title>
</head>
<body>
<h1 id="heading">Hello, World!</h1>
<button onclick="addHighlight()">Add Highlight</button>
<script src="script.js"></script>
</body>
</html>
JavaScript (script.js):
function addHighlight() {
const heading = document.getElementById("heading");
heading.classList.add("highlight");
}
Explanation:
document.getElementById("heading")selects the<h1>element by its ID"heading".classList.add("highlight")adds the"highlight"class to the element, applying the styles defined in the CSS.
Output:
Clicking the "Add Highlight" button will apply the .highlight class, changing the appearance of the <h1> element based on the CSS rules.
2. Adding Multiple Classes
You can add multiple classes to an element by passing multiple class names as arguments to classList.add().
Example:
function addMultipleClasses() {
const heading = document.getElementById("heading");
heading.classList.add("highlight", "bold-text", "extra-padding");
}
Explanation:
- You can add several classes at once by passing them as separate arguments to
classList.add(). In this example, the element will receive three new classes:"highlight","bold-text", and"extra-padding".
3. Checking if an Element Has a Class Before Adding
If you want to ensure a class is not added twice, even though classList.add() already prevents duplicates, you can use classList.contains() to check if the element already has the class.
Example:
function addHighlightIfNotExists() {
const heading = document.getElementById("heading");
if (!heading.classList.contains("highlight")) {
heading.classList.add("highlight");
}
}
Explanation:
classList.contains("highlight")checks if the element already has the"highlight"class. If it doesn’t, the class is added.
4. Using className Property (Legacy Method)
Before classList was introduced, the common way to add a class was by manipulating the className property. This method involves manually setting the entire class list as a string, which can overwrite existing classes if not done carefully.
Example:
function addHighlightLegacy() {
const heading = document.getElementById("heading");
heading.className += " highlight"; // Adds a new class, ensuring there’s a space before the new class name
}
Explanation:
- The
classNameproperty returns or sets the full class attribute of an element as a string. By appending" highlight"toclassName, we add the"highlight"class. You must add a space before the new class to avoid merging it with existing classes.
Caution:
- Using
classNameto modify the class list can lead to problems if you unintentionally overwrite other existing classes.
5. Conclusion
Adding a class to an element in JavaScript is easy and can be done using the modern classList.add() method, which is the recommended approach. This method ensures that classes are added efficiently and safely without duplicating existing classes. You can also check if a class exists before adding it, or add multiple classes at once.
Key Points:
classList.add(): The modern and efficient way to add one or more classes to an element.- Multiple Classes: You can add multiple classes using
classList.add("class1", "class2"). classList.contains(): Use this method to check if a class is already present.className: An older method that should be avoided unless compatibility with very old browsers is needed.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment