How to Returns the class name(s) of an element in JavaScript ?


In JavaScript, we can use the className property to get the class name(s) of an element. The className property returns a string that contains all the class names of the element separated by space.

Here are some methods to get the class name(s) of an element in JavaScript:

1. Using the className property

const element = document.getElementById('myElement');
const classNames = element.className;
console.log(classNames); // returns a string containing all the class names of the element

2. Using the classList property

The classList property returns a collection of the class names of an element. We can use the toString() method to convert the collection to a string.

const element = document.getElementById('myElement');
const classNames = element.classList.toString();
console.log(classNames); // returns a string containing all the class names of the element

3. Using the getAttribute() method

We can also use the getAttribute() method to get the value of the class attribute of an element.

const element = document.getElementById('myElement');
const classNames = element.getAttribute('class');
console.log(classNames); // returns a string containing all the class names of the element

Note: The getAttribute() method returns null if the attribute is not present on the element.

Example

Let's say we have an HTML element with the following class names:

<div id="myElement" class="box red large"></div>

We can use any of the above methods to get the class name(s) of the element:

const element = document.getElementById('myElement');

// Using the className property
const classNames1 = element.className;
console.log(classNames1); // "box red large"

// Using the classList property
const classNames2 = element.classList.toString();
console.log(classNames2); // "box red large"

// Using the getAttribute() method
const classNames3 = element.getAttribute('class');
console.log(classNames3); // "box red large"


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.