EN
JavaScript - loop through all the elements returned from getElementsByTagName
0
points
In this article, we would like to show you how to loop through all the elements returned from getElementsByTagName using JavaScript.
1. Using forEach()
In this example, we use forEach() to loop through all div elements inside the body and display their outerHTML in the console.
// ONLINE-RUNNER:browser;
<html>
<body>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<script>
var divs = document.getElementsByTagName('div'); // gets elements
var divsList = Array.prototype.slice.call(divs); // copies elements, creates array
divsList.forEach(function(element, index) {
console.log(element.outerHTML);
});
</script>
</body>
</html>
2. Using for loop
In this example, we use a simple for loop to loop through all div elements inside the body and display their outerHTML in the console.
// ONLINE-RUNNER:browser;
<html>
<body>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<script>
var divs = document.getElementsByTagName('div'); // gets elements
var divsList = Array.prototype.slice.call(divs); // copies elements, creates array
for(var i = 0; i < divsList.length; ++i) {
console.log(divsList[i].outerHTML);
}
</script>
</body>
</html>