How to add a class to DOM element in JavaScript?


HTML is a mark-up language used to create the useful elements of a webpage. The DOM which means Document Object Model is used to manipulate the HTML Document. In DOM, all the elements are defined as objects. The styling in the HTML document can be done by using CSS. In here, JavaScript is being used to manipulate them.

The ways in which the class can be added to a class to the DOM elements are described below.

Using className

If the element has a class already, then it will just add another class to it if not the element gets appended to the new class.

Syntax

The syntax to add a class element in JavaScript is as follows −

HTMLElemObj.className

Example 1

In this example we are trying to add a class to DOM elements in JavaScript −

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Add an element to class </title> <style> .context{ padding: 40px; border: 2px solid #A47167; } .highlight{ background: lightblue; } </style> </head> <body> <div class="context" id="contextid"> <p>By using className property we can add a class to a given element</p> <button type="button" onclick="nClass();">Click here to add a new class </button> </div> <script> function nClass(){ var elem = document.getElementById("contextid"); elem.className += " highlight"; } </script> </body> </html>

Using the List class

This way has a method called ‘add’ which is used to add class names to the elements.

Syntax

The syntax for the class list is as follows −

elem.classList.add("className")

Example 2

In this example we will learn how to add a class to a DOM element by using JavaScript −

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Add a class to element</title> <style> .tutorix { background-color: orange; font-size: 35px; } </style> </head> <body> <button onclick="myClass()">Click</button> <div id="tp">Tutorilas Point</div> <script> function myClass() { var elem = document.getElementById("tp"); elem.classList.add("tutorix"); } </script> </body> </html>

On executing the above code, it displays a button named click along with the Dom element displaying a text “Tutorialspoint”.

On clicking the button, a new class is added to the element which changes its style.

Updated on: 26-Aug-2022

787 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements