Languages
[Edit]
EN

JavaScript - iterate over elements from HTMLCollection

0 points
Created by:
Dollie-Rutledge
806

In this article, we would like to show you the best way to iterate over elements from HTMLCollection working with JavaScript.

Quick solution:

for (let element of elements) {
    // ...
}

 

Practical example

In this example, we use the for...of statement to iterate over the children of the container element and display their outerHTML in the console.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="container">
    <div>Div-1 example text...</div>
    <div>Div-2 example text...</div>
    <div>Div-3 example text...</div>
  </div>
  <script>

    let container = document.querySelector('#container');
    let elements = container.children;

    for (let element of elements) {
        console.log(element.outerHTML);
    }

  </script>
</body>
</html>

References

  1. for...of - JavaScript | MDN

Alternative titles

  1. JavaScript - iterate HTML collection elements
  2. JavaScript - for loop for elements in HTMLCollection
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