JavaScript – Get Class Names of an HTML Element as List

To get the class names of a specific HTML Element as List, using JavaScript, get reference to this HTML element, and read the classList property of this HTML Element.

classList property returns the collection of classes in class attribute as DOMTokenList object.

In the following example, we will get the class names of the HTML Element, which is selected by id "myElement", as a List.

example.html

Try this html file online, and click on the Click Me button. Class names of this HTML Element will be printed to console, as shown in the following screenshot.

If the class attribute is empty or no class attribute is defined, then classList property returns an empty list.

example.html

ADVERTISEMENT

Conclusion

In this JavaScript Tutorial, we learned how to get the class names of an HTML Element as List, using JavaScript.