The class attribute in CSS allows you to apply styles to elements with a specific class name. This article will explain how to add a class to an HTML element using JavaScript. JavaScript provides multiple methods to achieve this, including the .className property and the .add() method.
Let’s delve into these approaches for adding a class to an element.
Using the .className Property
The .className property allows you to set or return the class name of an element. This property can be utilized to add a class to an element without replacing its existing classes. Here’s how you can use the .className property:
Setting a Single Class: You can directly assign a class name to an element.
var element = document.getElementById('myElement');
element.className = 'newClass';
Appending a Class: To add a class without removing existing ones, append the new class to the current value of className.
var element = document.getElementById('myElement');
element.className += ' newClass';
Adding Multiple Classes: If you want to add multiple classes at once, separate the class names with a space.
var element = document.getElementById('myElement');
element.className += ' class1 class2';
Using the .add() Method
The .add() method is a part of the classList property, which provides a more modern and flexible way to manipulate the classes of an element. This method adds one or more classes to an element.
Adding a Single Class: Use the add() method to add a single class.
var element = document.getElementById('myElement');
element.classList.add('newClass');
Adding Multiple Classes: You can add multiple classes at once by passing them as separate arguments to the add() method.
var element = document.getElementById('myElement');
element.classList.add('class1', 'class2');
Detailed Examples
Example 1: Using .className
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Class Name Example</title>
<style>
.newClass {
color: red;
}
</style>
</head>
<body>
<div id="myElement">Hello, World!</div>
<script>
var element = document.getElementById('myElement');
element.className += ' newClass';
</script>
</body>
</html>

Example 2: Using .add()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Class List Example</title>
<style>
.newClass {
color: blue;
}
.anotherClass {
font-weight: bold;
}
</style>
</head>
<body>
<div id="myElement">Hello, World!</div>
<script>
var element = document.getElementById('myElement');
element.classList.add('newClass', 'anotherClass');
</script>
</body>
</html>

Adding classes to HTML elements using JavaScript can be done efficiently with both the .className property and the .add() method. While .className offers a straightforward way to manipulate class names, .add() provides a more flexible and modern approach, especially when dealing with multiple classes. Understanding these methods allows for more dynamic and interactive web pages, enhancing the user experience.
If a class is already declared for an element, and we need to add a new class name to the same element then it should be declared by inserting a space before writing the new class name otherwise, it will overwrite the existing class name. It can be written as follows:
<div id = "div1" class = "oldClass"> </div>
document.getElementById("div1").className = " newClass";
In the above code, we have inserted a space before newClass.
Example – Adding the class name
In this example, we are using the .className property for adding the “para” class to the paragraph element having id “p1”. We are applying the CSS to the corresponding paragraph using the class name “para”.
We have to click the given HTML button “Add Class” to see the effect.
<!DOCTYPE html>
<html>
<head>
<title>
add class name using JavaScript
</title>
<style>
.para {
font-size: 30px;
background-color: yellow;
color: blue;
border: 2px dotted red;
}
</style>
</head>
<body>
<h1>
Hello World :)
</h1>
<p id = "p1">
Welcome to the codemagnet
</p>
<p> Click the following button to see the effect. </p>
<button onclick = "fun()">
Add Class
</button>
<script>
function fun() {
var a = document.getElementById("p1");
a.className = "para";
}
</script>
</body>
</html>
Output:
How to Get the class name:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>
Hello World :)
</h1>
<p id = "p1" class = "para jtp">
Welcome to the Codemagnet
</p>
<p> Click the following button to get the class name. </p>
<p id = "p2"> </p>
<button onclick = "fun()">
Get Class name
</button>
<script>
function fun() {
var a = document.getElementById("p1").className;
document.getElementById('p2').innerHTML = "The class names of paragraph with 'id = p1' is: " + a;
}
</script>
</body>
</html>
Let us see an example of how to add a add() method
In this example, we use the add() method to add a class name to the paragraph element with the ID “p1”. To observe the effect, click the provided HTML button labeled “Add Class”.
<!DOCTYPE html>
<html>
<head>
<title>
add class name using JavaScript
</title>
<style>
.para {
font-size: 30px;
background-color: yellow;
color: blue;
border: 2px dotted red;
}
</style>
</head>
<body>
<h1>
Hello World :)
</h1>
<p id = "p1">
Welcome to the Codemagnet
</p>
<p> Click the following button to see the effect. </p>
<button onclick = "fun()">
Add Class
</button>
<script>
function fun() {
var a = document.getElementById("p1");
a.classList.add("para");
}
</script>
</body>
</html>

Adding a class to an HTML element using JavaScript is a fundamental skill for web developers, enhancing the ability to dynamically manipulate the appearance and behavior of web pages. This guide has covered various methods to achieve this, focusing on practical implementation and understanding.
Key Methods for Adding Classes
.className Property
The .className property is a straightforward method for managing class names. It allows you to:
- Set a Single Class: By assigning a class name to an element, you can change its styling.
element.className = 'newClass';
Append a Class: To add a new class while preserving existing ones, concatenate the new class to the current className.
element.className += ' additionalClass';
Add Multiple Classes: Multiple classes can be added by separating them with spaces.
element.className += ' class1 class2';
While .className is simple and effective, it has limitations when handling multiple classes or ensuring no duplicates.
.classList Property and .add() Method
The .classList property provides a more modern and flexible way to manipulate classes. It includes the .add() method, which is particularly useful for:
- Adding Single or Multiple Classes: You can add one or more classes to an element efficiently.
element.classList.add('newClass');
element.classList.add('class1', 'class2');
Avoiding Duplicates: The .classList ensures that duplicate class names are not added, maintaining clean class lists.
Practical Applications
Understanding how to add classes dynamically is crucial for creating interactive web pages. Whether you are highlighting selected items, toggling visibility, or applying theme changes, these methods provide the flexibility needed for responsive and user-friendly designs.
Best Practices
- Consistency: Choose a method and stick with it for consistency, unless specific use cases demand otherwise.
- Avoid Inline Styles: Use class manipulation over inline styles to keep HTML clean and maintain separation of concerns.
- Performance Considerations: For performance, prefer
.classList.add()when dealing with frequent class manipulations, as it is optimized for such operations.
Common Pitfalls
- Overwriting Existing Classes: Using
.classNameimproperly can overwrite existing classes. Always append new classes instead of reassigning. - Browser Compatibility: While modern browsers support
.classList, always check compatibility if targeting older browser versions.
Conclusion
Adding classes to elements using JavaScript is a versatile technique that enhances dynamic web development. By mastering both the .className property and the .classList.add() method, you can effectively control and update the appearance of elements in response to user actions or other events. This not only improves the user experience but also keeps your codebase clean and maintainable.
Whether you are a beginner or an experienced developer, understanding these methods will empower you to create more interactive and responsive web applications.





Leave a Reply