Get AI Code Completions for Your IDE

Home   >   Tutorials   >   JavaScript   >   How to Set an HTML Element’s Class Using JavaScript

JavaScript - How to Set an HTML Element’s Class Using JavaScript

The HTML class attribute is used to mark individual elements with a class, distinguishing it from other elements in the document.

This allows front-end web developers to easily apply CSS styles to an element, or to easily identify and retrieve an element from the DOM. A single HTML element can have multiple classes. Similarly, multiple HTML elements can share the same class – there is no restriction based on element type, and classes do not need to be unique.

There are two straightforward ways to set an element’s class:

  1. Modifying the className property (which serves both as a getter and setter)
  2. Modifying the classList property using its built-in methods

We generally recommend the second approach, using the classList property, as the resulting code is generally more readable, more accurate, and more functional than when modifying the className property directly.

The className property

You can access an element’s className by calling it directly on the element returned by a given querySelector. Take, for example, the following sample HTML code:

HTML

<h1>
  Make me classy
</h1>

This code creates an <h1> element, but does not include the class. Now let’s look at some sample JavaScript code that tries to manipulate this element:

JavaScript

console.log(document.querySelector('h1').className);
// The expected output is an empty string

document.querySelector('h1').className = 'classy';
console.log(document.querySelector('h1').className);
//Expected output: classy

In the above code, the first print to the console returns an empty string since the <h1> element has no class attribute when the code runs. Thus, the className property returns an empty string.

The second line of code (line 4) pulls in the first <h1> element found using the document.querySelector() method. Where before the className property retrieved the class name for the element, we can repurpose it here to assign a class to the element. Applying the assignment operator turns the className property from a getter into a setter. The example above assigns the class “classy” to the <h1> element obtained from the document.

Now that we’ve set the class value of the <h1> element, the second print statement will pick up the class value and print it to the console. The output of this print will be “classy” – the class we assigned on the fifth line of the script.

Note: The className property is destructive – if the element had a class before, it is now gone! The previous class information was replaced with the new “classy” value, and this will be the only class on the element.

Syntax

Getter: Element.className

Setter: Element.className = class (String)

The classList property

The classList property is read-only by default, but it comes with supporting methods and properties that can be used to manipulate the list of classes assigned to an HTML element. Take the following sample document below:

HTML

<h1 class="multi-class header first title">
  I am super classy!
</h1>

This creates an <h1> element with multiple classes. We can use the classList property in JavaScript to review these class assignments, as in the following code:

JavaScript

console.log(document.querySelector('h1').classList.length);
// Expected output: 4

console.log(document.querySelector('h1').classList.value);
// Expected output: multi-class header first title

Calling the length property of the classList for the element returns the number of classes the element has.

Calling the value property of the classList for the element returns the names list as a string.

classList methods

While the read-only functionality is useful, it doesn’t yet give us the flexibility of the className property. To work with classList, we need to make use of supporting methods on the classList object.

We’ll review each function by using the <h1> sample element from the previous example. This element has four classes in its class list – “multi-class”, “header”, “first”, and “title”. The methods below manipulate this class list.

add()

The add() method adds another class to the list:

JavaScript

document.querySelector('h1').classList.add('bulky');

console.log(document.querySelector('h1').classList.value);
// Expected output: multi-class header first title bulky

In the above code, we added the class “bulky” to the list. This appends the class name we provided to the end of the class definition, resulting in appending the class name “bulky” to the printed output.

remove()

The remove() removes a class from the class list:

JavaScript

document.querySelector('h1').classList.remove('bulky')

console.log(document.querySelector('h1').classList.value);
// Expected output: multi-class header first title

In this example, “bulky” was removed from the element’s class list, leaving it with our original four classes.

Note: You can add or remove multiple classes at a time – simply pass them in as a comma-delimited string (i.e. “extra,bulky,classes” – this adds or removes three classes from the class list).

toggle()

The toggle() method toggles a given class on an object. This means that the requested class is either added if missing, or removed if present:

JavaScript

document.querySelector('h1').classList.toggle('toggles');

console.log(document.querySelector('h1').classList.value);
// Expected output: multi-class header first title toggle

document.querySelector('h1').classList.toggle('toggles')

console.log(document.querySelector('h1').classList.value);
// Expected output: multi-class header first title

This code adds, then removes, the “toggles” class using the toggle() method. The first console.log() statement will include “toggles” in the class list, while the second console.log() will not.

replace()

The replace() method replaces one class name with another. It takes two parameters – the class name to replace, and the new value to replace it with:

JavaScript

console.log(document.querySelector('h1').classList.value);
// Expected output: multi-class header first title

document.querySelector('h1').classList.replace('title', 'bundle')

console.log(document.querySelector('h1').classList.value);
// Expected output: multi-class header first bundle

In the above example. We replace the class name “title” in our <h1> element with a new class – “bundle”.

 

Related Articles: 

JavaScript – How to Use setAttribute

JavaScript – How to Change CSS

JavaScript – How to Change The Page URL

Get AI Code Completions for Your IDE