# How To Add A Class To The Body Element Using JavaScript

If you don’t know how to add class to the body Element using JavaScript, please check out the information in this post. I will show you how to do it.

## Add A Class To The Body Element Using JavaScript

Syntax:

element.classList.add("name_of_the_class");

See the following example:

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />

<body>
<div class="container">
<h1>Welcome to our Page!</h1>
</div>

<script>
</script>
</body>
</html>

Output:

As you can see, the result is that the body tag now has a class attribute with the corresponding value “body-class”, which we passed in the add() method.

If you want to add multiple classes to the body element, the add() method also helps you to do it. Change the script as follow:

<script>
</script>

Output:

Note: if you try to add two class names with the same value, the add() method will automatically check for duplicates and only add one time.

<script>
</script>

Output:

### Method 2: Reassign the value of the className property

You can reassign the value of the className property to add class to the body element using JavaScript.

Syntax:

element.className = "name_of_the_class";

See the following example:

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />

<body>
<div class="container">
<h1>Welcome to our Page!</h1>
</div>

<script>
</script>
</body>
</html>

Output:

You still have the same result as using solution one

If you want to add more classes, use the “+=” operator. However, from the 2nd element onwards, prepend it with a space. Otherwise, you will have only one className, which is the concatenated strings:

<script>
</script>

Output:

Note: Unlike method one, this method still allows you to add two identical class names to the body element.

<script>
</script>