How To Add Class To Element In JavaScript – Complete Guide

How To Add Class To Element In JavaScript – Complete Guide

Javascript is one of the key elements behind adding interactivity to a website. Without it, thinking of creating a fully interactive and functional website is next to impossible.

Among the many amazing features of this language is the variety of functions and methods it offers to make a developer’s life easier and more convenient. Using javascript, we can modify DOM elements or perform calculations behind the scenes while static HTML is displayed.

The goal of this tutorial is to demonstrate in-depth how Javascript can be used to add classes to HTML elements and perform a number of other useful operations with its help. With that being said, let’s begin!

Introduction

CSS uses the class attribute to perform a series of actions on elements with the same class name. DOM (Document Object Model) is a method of manipulating HTML documents.

Javascript allows you to add classes to the body of your webpage through document.body or document.getElementById("id"). Classes can either be added directly to an HTML element as an attribute (Ex: <p class="para-class">) or by using JavaScript (which is what we’ll look at in this section).

There are three different ways to add classes to an element using javascript. Let’s explore each of those approaches one by one.

Using .className property

The .className property can be used to set the name of the class of an element. Using this property, we can add a single class or multiple classes to an HTML element without replacing its existing classes. In addition, this property can also be used to return an element’s class attribute value.

Syntax to set the class name:

HTMLelement.className = "new_class";Code language: HTML, XML (xml)

In this case, “new_class” specifies the element’s class name. We can add multiple classes by separating their names with spaces, for instance, “new_class1 new_class2“.

To return the class name/names:

HTMLelement.className;Code language: HTML, XML (xml)

The property returns a string type representing a class or lists of classes of elements separated by space.

Example

Below is an example, that uses the .className property to add the class new-para-class to the paragraph element having id para. The CSS is applied to the corresponding paragraph using the class name new-para-class.

In order to see the effect, we need to click the given HTML button Add New Class to see the effect.

Note: If you assign a class name directly to the className property, the existing classes will be overwritten.

HTML Code:

<!doctype HTML>
<html>
	<head>
		<title>codedamn HTML Playground</title>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link rel="stylesheet" href="/style.css" />
	</head>
	<body>
		<h1>Welcome to codedamn</h1>
        <p id="para" class="old-para-class">This para's class will get replaced with the new one.</p>
        <button onclick="addClass()">Add New Class</button>
		<script src="https://bit.ly/codedamn-web-console"></script>
		<script src="/script.js"></script>
	</body>
</html>Code language: HTML, XML (xml)

CSS Code:

body {
	padding: 10px;
	margin: 0;
	font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell,
		Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
	line-height: 1.6;
	font-size: 18px;
}

.old-para-class{
    background: #96bfff;
}

.new-para-class {
    background: #ff96ab;
}Code language: CSS (css)

Javascript Code:

const para = document.getElementById("para");

function addClass(){
    para.className="new-para-class";
}Code language: JavaScript (javascript)

Output:

To view the HTML output before and after clicking the button, slide towards the left and right respectively.

Adding multiple classes

You can add new classes without replacing older ones by using the += operator. This works by keeping older classes and adding new ones.

Note: When adding a class, make sure to add a space " " before the class name. Let’s modify the existing example to see how it works.

HTML Code:

...
...
<p id="para" class="old-para-class">This para's class will get replaced with the new one.</p>
...
...Code language: JavaScript (javascript)

CSS code:

...
...
.old-para-class{
    color: #2e4bab;
}

.new-para-class {
    background: #ff96ab;
}
...
...Code language: JavaScript (javascript)

Javascript code:

...
...
function addClass(){
    para.className += " new-para-class"; //using the += operator
}Code language: JavaScript (javascript)

Output:

To view the HTML output before and after clicking the button, slide towards the left and right respectively.

Getting the class name

Using the .className property, we can also retrieve the class names of the paragraph elements having id = "para".

HTML Code:

...
...
<p id="para" class="old-para-class">Clicking the below button will add a new class without removing the existing one.</p>
<p>Para Class:</p>
<p id="show-class" class="show-class-para"></p> <!-- This element will show the classes applied on first para. -->
<button onclick="addClass()">Add New Class</button>
...
...Code language: JavaScript (javascript)

Javascript Code:

const para = document.getElementById("para");
const showClassPara = document.getElementById("show-class");

function addClass(){
    para.className += " new-para-class"; 
    showClassPara.innerHTML += para.className; //using the className property to get the element and adding to p element with id show-class
}Code language: JavaScript (javascript)

Output:

To view the HTML output before and after clicking the button, slide towards the left and right respectively.

Using .classList.add() method

In HTML, the .classList property returns the DOMTokenList representation of the element’s class attribute.

This .classList property has a .add() method that can be used to add a class name to an HTML element. Here is an example of how you would use .add method in Javascript:

HTMLelement.classList.add("new_class");Code language: CSS (css)

Examples

We will use the same files as before and only change the CSS and Javascript.

CSS Code:

...
...
.new-para-class1 {
    background: #ff96ab;
}Code language: CSS (css)

Javascript Code:

...
...
function addClass(){
    para.classList.add("new-para-class1");
...
...Code language: PHP (php)

Output:

To view the HTML output before and after clicking the button, slide towards the left and right respectively.

Adding multiple classes

The add() method is also capable of adding multiple classes simultaneously. When adding multiple classes, separate the classes with a comma.

CSS Code:

...
...
.new-para-class1 {
    background: #ff96ab;
}

.new-para-class2 {
    font-style: italic;
}
...
...Code language: CSS (css)

Javascript Code:

...
...
function addClass(){
    para.classList.add("new-para-class1", "new-para-class2"); //seperating multiple classes with the help of comma
...
...Code language: PHP (php)

Output:

To view the HTML output before and after clicking the button, slide towards the left and right respectively.

Using .setAttribute() Method

An element can be modified by adding an attribute using the setAttribute method in Javascript.

Since classes are also element attributes, we can add them setAttribute method to add a class.

There are two parameters required by this method, the attribute’s name, and its value. Here is an example of how we would use this method in Javascript:

HTMLelmeent.setAttribute('class', 'new_class');Code language: HTML, XML (xml)

Examples

Let’s take the previous example and change some lines to see how it works:

Javascript Code:

...
...
function addClass(){
    para.setAttribute('class', 'new-para-class1') //using the setAttribute class to set the class name for the previous para element.
...Code language: PHP (php)

Output:

To view the HTML output before and after clicking the button, slide towards the left and right respectively.

Adding multiple classes

In order to add multiple classes to the same element, we can pass a list of multiple class names separated by spaces to the setAttribute method.

Javascript Code:

...
...
function addClass(){
    para.setAttribute('class', 'new-para-class1 new-para-class2')
...Code language: PHP (php)

Output:

To view the HTML output before and after clicking the button, slide towards the left and right respectively.

Some Other Useful methods

Deleting a class

The .classList property also has a remove() method which allows you to delete a class from an HTML element. Syntax example:

HTMLelement.classList.remove("class_name")Code language: HTML, XML (xml)

Toggling a class

Similarly, The toggle() method of classList property can be used to toggle a class in javascript. Syntax example:

HTMLelement.classList.toggle("class_name")Code language: HTML, XML (xml)

Conclusion

We just discussed how to add classes to elements. These properties allow you to add single or multiple classes to an element. You can also add a class when the element is hovered by using the onmouseover event.

I hope this article explained everything you need to know about adding class names to HTML elements. If you ever feel lost and want help understanding where to start your coding journey, there are amazing courses and blogs for web development and other coding concepts on Codedamn. Remember to practice coding on a daily basis. You can play around with your code on Codedamn’s online compiler as well.

Finally, If you are interested in my content and would like to connect, then you can find me on Linkedin or Twitter.

Thank You for reading!

Sharing is caring

Did you like what Indrakant wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far