Javascript DOM HTML Element className Property get

Introduction

Get the class name of the first <div> element in the document (if any):

var x = document.getElementsByTagName("DIV")[0].className;

Click the button to display the value of the class attribute of the div element below.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {//  ww w . jav a 2 s  .  co m
  width: 300px;
  height: 100px;
  background-color: coral;
  color: white;
  margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="mystyle">
I am a DIV element with class="mystyle"
</div>

<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {
  var x = document.getElementsByTagName("DIV")[0].className;
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>



PreviousNext

Related