Languages
[Edit]
EN

JavaScript - loop through all the elements returned from getElementsByTagName

0 points
Created by:
p_agon
589

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>

 

References

  1. Array.prototype.forEach() - JavaScript | MDN
  2. for - JavaScript | MDN
  3. Array.prototype.slice() - JavaScript | MDN
  4. Function.prototype.call() - JavaScript | MDN

Alternative titles

  1. JavaScript - iterate all the elements returned from getElementsByTagName
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join