JavaScript Code

How to get classnames of a div using JavaScript?

Tutorials using JS

Get classnames of a div using JavaScript

In this tutorial, you shall learn how to get all classnames of a div element using JavaScript.


To get all classnames of a div element using JavaScript, we can use Element.classList property. classList property returns all the classnames as a list for the div element.

let classnames = divElement.classList;


When user clicks on the Click me button, we get the div element with the id "myDiv", get the classnames for the div using classList property, and display them in the paragraph with id "output".

<!DOCTYPE html>
<h1>JavaScript Tutorial</h1>
<button id="myBtn">Click me</button>
<div id="myDiv" class="card tile active">About</div>
<p id="output"></p>

document.getElementById("myBtn").addEventListener("click", function() {
    //get the div element
    const myDiv = document.getElementById("myDiv");
    //get the class names of the div element
    let classnames = myDiv.classList;
    document.getElementById("output").innerHTML = classnames;


Copyright @2022