Last updated: Mar 5, 2024
Reading time·2 min
To loop through all DOM elements:
getElementsByTagName()
method to get an HTMLCollection
containing
all DOM elements.for...of
loop to iterate over the collection.Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <div>Box 1</div> <div>Box 2</div> <div>Box 3</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const allElements = document.getElementsByTagName('*'); // ✅ Loop through all elements (including html, head, meta, scripts) for (const element of allElements) { console.log(element); } console.log('--------------------'); // ✅ Loop through all elements in body const allInBody = document.querySelectorAll('body > *'); for (const element of allInBody) { console.log(element); }
The
document.getElementsByTagName()
method returns an HTMLCollection
containing the elements with the provided tag
name.
*
as a parameter, it returns a collection containing all DOM elements.We used a for...of loop to iterate over the collection.
Note that you can use the break
keyword to break out of a for
loop if a certain condition is met.
const allElements = document.getElementsByTagName('*'); for (const element of allElements) { console.log(element); if (element.textContent === 'Box 2') { break; } }
The selector above contains all of the DOM elements, including the html
element, the head
element, etc.
body
tagIf you only need to iterate over the elements contained in the body
tag, use
the document.querySelectorAll()
method.
const allInBody = document.querySelectorAll('body > *'); for (const element of allInBody) { console.log(element); }
The document.querySelectorAll() method
takes a string containing a CSS selector as a parameter and returns a NodeList
containing the matching elements.
We used a for...of
loop to iterate over the NodeList
, however, you can also
use the
NodeList.forEach()
method.
const allInBody = document.querySelectorAll('body > *'); allInBody.forEach(element => { console.log(element); });
The function we passed to the forEach()
method gets called with each element
in the NodeList
.
break
keyword is not supported when using the forEach
method.The querySelectorAll()
method takes one or more comma-separated selectors.
The following example selects all elements with classes my-class
and
your-class
.
const elements = document.querySelectorAll( '.my-class, .your-class' ); elements.forEach(element => { console.log(element); });
You can pass as many comma-separated selectors to the method as necessary.
This might be a more efficient solution if you don't need to iterate over every single element in the DOM.
You can learn more about the related topics by checking out the following tutorials: