Sometimes we want to loop through all DOM elements on a page with JavaScript.
In this article, we’ll look at how to loop through all DOM elements on a page with JavaScript.
Select All Elements with document.getElementsByTagName
We can select all elements on a page with the document.getElementsByTagName
method.
For instance, if we have the following HTML:
<div>
<span>hello world</span>
</div>
<p>
how are you
</p>
Then we can loop through all of them by writing:
const allEls = document.getElementsByTagName("*");
for (const el of allEls) {
console.log(el)
}
We select all elements by calling document.getElementsByTagName
with '*'
.
And then we can loop through all the returned elements with the for-of loop.
Select All Elements with document.querySelectorAll
We can select all elements on a page with the document.querySelectorAll
method.
For instance, if we have the following HTML:
<div>
<span>hello world</span>
</div>
<p>
how are you
</p>
Then we can loop through all of them by writing:
const allEls = document.querySelectorAll("*");
for (const el of allEls) {
console.log(el)
}
We select all elements by calling document.querySelectorAll
with '*'
.
And then we can loop through all the returned elements with the for-of loop.
Conclusion
We can use the document.getElementsByTagName
or document.querySelectorAll
method to get all elements on a page.
Then we can loop through them all with the for-of loop.