Javascript DOM HTML Element classList Property get class name count

Introduction

Find out how many class names a <div> element has:

var x = document.getElementById("myDIV").classList.length;

Click the button to display the number of class names the div element has.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {/*from ww  w.  jav  a  2  s  .  c om*/
  width: 500px;
  height: 50px;
}

.anotherClass {
  background-color: lightblue;
}

.thirdClass {
  text-align: center;
  font-size: 25px;
  color: black;
  margin-bottom: 10px;
}
</style>
</head>
<body>
<div id="myDIV" class="mystyle anotherClass thirdClass">
I am a DIV element with three classes
</div>

<button onclick="myFunction()">Test</button>
<p id="demo"></p>

<script>
function myFunction() {
  var x = document.getElementById("myDIV").classList.length;
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>



PreviousNext

Related