Javascript DOM How to - Loop through all elements returned from getElementsByClassName








Question

We would like to know how to loop through all elements returned from getElementsByClassName.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
.first, .second {<!--from   w  ww .ja  va 2  s.  c om-->
  border: 1px solid black;
  width: 200px;
}
</style>
<script type='text/javascript'>
window.onload=function(){
    var elements = document.getElementsByClassName('first');
    Array.prototype.forEach.call(elements, function (element) {
        element.innerHTML = 'Your text goes here';
    });
}
</script>
</head>
<body>
  <div class='first'>First</div>
  <div class='first'>First too</div>
  <div class='second'>Second</div>
</body>
</html>

The code above is rendered as follows: