How to correctly iterate through getElementsByClassName() in JavaScript?

To correctly iterate, use the document.getElementsByClassName(). The getElementsByClassName() is a methof od Document interface.

Following is the cod wherein we are iterating through div classes −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<link rel="stylesheet" href="//">
<script src=""></script>
<script src=""></script>
<div class="demo">My First JavaScript Program</div>
<div class="demo">This is the second Program</div>
<div class="demo">This is the third Program </div>
   var className = document.getElementsByClassName('demo');
   for(var index=0;index < className.length;index++){

To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor.


This will produce the following output −