EN
JavaScript - iterate over elements from HTMLCollection
0
points
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>