JavaScript | Adding a class name to the element
The class name attribute can be used by CSS and JavaScript to perform certain tasks for elements with the specified class name. Adding the class name by using JavaScript can be done in many ways.
- Using .className property: This property is used to add a class name to the selected element.
Syntax:
element.className += "newClass";
Example: This example uses .className property to add class name.
<!DOCTYPE html><html><head><title>JavaScript to add class name</title><style>.addCSS {color: green;font-size: 25px;}</style></head><bodystyle="text-align:center;"><h1style="color:green;">GeeksForGeeks</h1><pid="p">A Computer Science portal for Geeks.</p><buttononclick="addClass()">AddClass</button><!-- Script to add class name --><script>function addClass() {var v = document.getElementById("p");v.className += "addCSS";}</script></body></html>Output:
- Before clicking the button:

- After clicking the button:

- Before clicking the button:
- Using .add() method: This method is used to add a class name to the selected element.
Syntax:
element.classList.add("newClass");Example: This example uses .add() method to add class name.
<!DOCTYPE html><html><head><title>JavaScript to add class name</title><!-- Style add to new class --><style>.addCSS {background-color:green;color: white;padding:20px;font-size: 25px;}</style></head><bodystyle="text-align:center;"><h1style="color:green;">GeeksForGeeks</h1><pid="p">A Computer Science portal for Geeks.</p><buttononclick="addClass()">AddClass</button><!-- Script to add class name --><script>function addClass( {var v = document.getElementById("p");v.classList.add("addCSS");}</script></body></html>Output:
- Before clicking the button:

- After clicking the button:

- Before clicking the button:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!



