Javascript DOM HTML HTMLCollection item() Method loop through all elements by class name

Introduction

Loop through all elements with class="myclass", and change their background color:

Click the button to add a background color to all elements with class="myclass":

View in separate window

<!DOCTYPE html>
<html>
<head>
</head>//from  w w w  .ja v a2s.  co  m
<body>
<h1>HTMLCollection item() Method</h1>

<p>A P element.</p>
<p class="myclass">Another P element.</p>
<p class="myclass">A third P element.</p>
<button onclick="myFunction()">Set Color</button>

<script>
function myFunction() {
  var x, i;
  x = document.getElementsByClassName("myclass");
  for (i = 0; i < x.length; i++) {
  x.item(0).style.backgroundColor = "red";
  }
}
</script>

</body>
</html>



PreviousNext

Related