Javascript DOM HTML Document getElementsByClassName() vs getElementById()

Introduction

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 {/*from   w  w w.  ja va2  s. c om*/
  width: 300px;
  height: 100px;
  background-color: coral;
  color: white;
  margin-bottom: 10px;
}
</style>
</head>
<body>
<div id="myDIV" 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.getElementsByClassName("mystyle")[0].className;
  var y = document.getElementById("myDIV").className;
  document.getElementById("demo").innerHTML = "Using getElementsByClassName: " + x + "<br>" + "Using getElementById: " + y;
}
</script>

</body>
</html>



PreviousNext

Related