How To Loop Through All DOM Elements In JavaScript

loop through all DOM elements in JavaScript

To loop through all DOM elements in JavaScript, we have tested effectively with 2 methods, getElementsByTagName() and  querySelectorAll(). Check out the details below to get more information.

To Loop through all DOM elements in JavaScript.

Method 1 : Using getElementsByTagName()

Using getElementsByTagName() method to get an HTML Collection containing all DOM elemets.

Syntax: document.getElementsByTagName(tagname)

Parameters

  • Tagname : Required, the tagname of the elements.

Return Value

Object : An HTML Collection object. A collection of elements with a specified tag name. The elements are sorted as they appear in the document.

Example

<!DOCTYPE html>
<html>
<body> 
    <div>
      <span>Well come</span>
    </div>    
    <p> My name is LearnShareIT</p> 
    <p> Nice to see you </p>
<script src="src/script.js"></script> 
</body>
</html>

Script.js 

const allElements = document.getElementsByTagName('*');
 
//We select all elements by calling document.getElementsByTagName with '*' .
for (const element of allElements) {
  console.log(element);
}

Output

Website view

Well come
My name is LearnShareIT
Nice to see you

Console

<html ></html>
<head ></head>
<script ></script>
<body ></body>
<div ></div>
<span ></span>
<p ></p>
<p ></p>
<script ></script>

Method 2 : Using querySelectorAll() 

The querySelectorAll() takes a string containing a CSS selector as a parameter and returns a Nodelist containing the matching elements.

Syntax: document.querySelectorAll('tagname > *')

Parameters

  • tagname: Required, The tagname of the elements.

Return Value

The querySelectorAll() method returns a NodeList.

Example

<!DOCTYPE html>
<html>
  <head>
    <title>Learn Share IT</title>
  </head>	
<body> 
    <div>
      <h3>Learn Share IT</h3>
      <h4>Using querySelectorAll() </h4>
      <p>The querySelectorAll() method returns a NodeList.</p>
    </div>    
<script src="src/script.js"></script> 
</body>
</html>

Script.js

const allInDiv = document.querySelectorAll('div > *');
 
//We select all elements in div tag by calling document.querySelectorAll with 'div > *' .
for (const element of allInDiv) {
  console.log(element);
}

Output

WEBSITE VIEW

Learn Share IT
Using querySelectorAll()
The querySelectorAll() method returns a NodeList.

CONSOLE

<h3 ></h3>
<h4 ></h4>
<p ></p>

Summary

In this tutorial, we have explained how to loop through all DOM elements in JavaScript by using the getElementsByTagName() and querySelectorAll(). We always hope this tutorial is helpful to you. Leave your comment here if you have any questions or comments to improve the article. Thanks for your read.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *