How to use.add() method in Javascript
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 the class name.
HTML
<!DOCTYPE html> < html > < head > < title > JavaScript Adding a class name to the element </ title > < style > .addCSS { background-color: green; color: white; padding: 20px; font-size: 25px; } </ style > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > w3wiki </ h1 > < p id = "p" > A Computer Science portal for Geeks. </ p > < button onclick = "addClass()" > AddClass </ button > <!-- Script to add class name --> < script > function addClass() { let elem = document.getElementById("p"); elem.classList.add("addCSS"); } </ script > </ body > </ html > |
Output:
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.
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.
Below are the different approaches that could be used to add a class name to the element:
Table of Content
- Using .className property
- Using .add() method