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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h2>Get Classes of HTML Element as List using JavaScript</h2>
<div id="myElement" class="abc xyz pqr">Hello World</div>
<br>
<button type="button" onclick="execute()">Click Me</button>
<p id="out"></p>
<script>
function execute(){
var element = document.getElementById('myElement');
var classes = element.classList;
console.log(classes);
for(var i=0; i<classes.length; i++){
var cls = classes[i];
console.log(cls);
}
}
</script>
</body>
</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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h2>Get Classes of HTML Element as List using JavaScript</h2>
<div id="myElement">Hello World</div>
<br>
<button type="button" onclick="execute()">Click Me</button>
<script>
function execute(){
var element = document.getElementById('myElement');
var classes = element.classList;
console.log(classes);
for(var i=0; i<classes.length; i++){
var cls = classes[i];
console.log(cls);
}
}
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to get the class names of an HTML Element as List, using JavaScript.