JavaScript Code

How to iterate over classnames of a div using JavaScript?


Tutorials using JS

Problem Statement

iterate over classnames of a div element using JavaScript

Solution

to iterate over classnames of a div element using JavaScript, we can use Element.classList property and for loop. classList property returns all the classnames as a list for the div element, and we can use for loop to iterate over the classnames

let classnames = myDiv.classList;
for (let i = 0; i < classnames.length; i++) {
    console.log(classnames[i]);
}

Program

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 iterate over the classnames using for loop

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Iterate over classnames of div</h2>
<button id="myBtn">Click me</button>
<div id="myDiv" class="card tile active">About</div><br>
<pre id="output"></pre>

<script>
document.getElementById("myBtn").addEventListener("click", function() {
	//get div element
	const myDiv = document.getElementById("myDiv");
	//iterate over class names of div
    let classnames = myDiv.classList;
    for (let i = 0; i < classnames.length; i++) {
        document.getElementById("output").innerHTML += classnames[i] + '<br>';
    }
});
</script>

</body>
</html>


Copyright @2022