Categories
JavaScript Answers

How to Loop Through All DOM Elements on a Page with JavaScript?

Spread the love

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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.