Javascript DOM HTML Element classList Property get the first class name

Introduction

Get the first class name (index 0) of a <div> element:

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

Click the button to display the class name of the first class (index 0) of div.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {//from w  w  w .ja v  a2 s  . c  o m
  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.item(0);
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>



PreviousNext

Related