Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
HTMLCollection for Loop
The HTMLCollection is an array-like object containing HTML elements. We can access every element in the collection using its index and iterate through the collection to process all elements one by one using various loop methods.
HTMLCollection iteration is commonly used when you need to perform operations on multiple elements. For example, clearing all checkboxes when a user clicks a "Clear All" button, or styling all elements with the same class name. The collection updates automatically when elements are added or removed from the DOM.
In this tutorial, we will learn different loop methods to iterate through HTMLCollections efficiently.
What is HTMLCollection?
An HTMLCollection is a live collection of HTML elements returned by methods like getElementsByClassName(), getElementsByTagName(), and getElementsByName(). It has array-like properties including a length property and indexed access, but it's not a true array.
Using the for Loop
The traditional for loop provides precise control over iteration by using an index variable to access each element in the HTMLCollection sequentially.
Syntax
Following is the syntax for using a for loop to iterate through HTMLCollections
for (let i = 0; i < collection.length; i++) {
let element = collection[i];
// Process element
}
Here, i is the index initialized with 0, and we iterate through the collection until the index is less than the collection's length.
Example
Following example demonstrates using a for loop to access div elements and display their content
<!DOCTYPE html>
<html>
<head>
<title>For Loop with HTMLCollection</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
<h2>Using the for loop to iterate through HTMLCollections</h2>
<div class="divElement">Div 1</div>
<div class="divElement">Div 2</div>
<div class="divElement">Div 3</div>
<div class="divElement">Div 4</div>
<div class="divElement">Div 5</div>
<div id="output" style="margin-top: 15px; border: 1px solid #ccc; padding: 10px; background: #f9f9f9;"></div>
<script>
let output = document.getElementById('output');
let allDivs = document.getElementsByClassName('divElement');
output.innerHTML = "The content of all div elements: <br>";
for (let i = 0; i < allDivs.length; i++) {
output.innerHTML += (i + 1) + ". " + allDivs[i].innerHTML + "<br>";
}
</script>
</body>
</html>
The output displays the content of each div element with numbering
Using the for loop to iterate through HTMLCollections Div 1 Div 2 Div 3 Div 4 Div 5 The content of all div elements: 1. Div 1 2. Div 2 3. Div 3 4. Div 4 5. Div 5
Using the for...of Loop
The for...of loop provides a cleaner syntax for iteration by directly giving access to each element without manually managing an index variable.
Syntax
Following is the syntax for using a for...of loop with HTMLCollections
for (let element of collection) {
// Process element directly
}
Here, element represents each HTML element in the collection during each iteration.
Example
Following example shows how to use the for...of loop to iterate through paragraph elements
<!DOCTYPE html>
<html>
<head>
<title>For...of Loop with HTMLCollection</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
<h2>Using the for...of loop to iterate through HTMLCollections</h2>
<p class="pElement">Car</p>
<p class="pElement">Bike</p>
<p class="pElement">Truck</p>
<p class="pElement">Cycle</p>
<p class="pElement">Tempo</p>
<div id="output" style="margin-top: 15px; border: 1px solid #ccc; padding: 10px; background: #f0f8ff;"></div>
<script>
let output = document.getElementById('output');
let allParagraphs = document.getElementsByClassName('pElement');
output.innerHTML = "Vehicles found: <br>";
for (let element of allParagraphs) {
output.innerHTML += "? " + element.innerHTML + "<br>";
}
</script>
</body>
</html>
The output shows each paragraph's content formatted as a bullet list
Using the for...of loop to iterate through HTMLCollections Car Bike Truck Cycle Tempo Vehicles found: ? Car ? Bike ? Truck ? Cycle ? Tempo
Converting to Array for forEach() Method
HTMLCollection doesn't have a built-in forEach() method. To use forEach(), we need to convert the HTMLCollection to an array using Array.from() or the spread operator [...].
Syntax
Following are the syntax options for converting HTMLCollection to array
// Method 1: Using Array.from()
Array.from(collection).forEach((element) => {
// Process element
});
// Method 2: Using spread operator
[...collection].forEach((element) => {
// Process element
});
Example
Following example demonstrates using forEach() with HTMLCollection after converting it to an array
<!DOCTYPE html>
<html>
<head>
<title>forEach with HTMLCollection</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
<h2>Using forEach() method with HTMLCollection</h2>
<label>Checkbox 1 <input type="checkbox" name="check" value="one"></label><br>
<label>Checkbox 2 <input type="checkbox" name="check" value="two"></label><br>
<label>Checkbox 3 <input type="checkbox" name="check" value="three"></label><br>
<label>Checkbox 4 <input type="checkbox" name="check" value="four"></label><br>
<label>Checkbox 5 <input type="checkbox" name="check" value="five"></label><br><br>
<button onclick="selectAll()" style="margin-right: 10px;">Select All</button>
<button onclick="clearAll()">Clear All</button>
<script>
function selectAll() {
let allCheckboxes = document.getElementsByName('check');
Array.from(allCheckboxes).forEach((checkbox) => {
checkbox.checked = true;
});
}
function clearAll() {
let allCheckboxes = document.getElementsByName('check');
[...allCheckboxes].forEach((checkbox) => {
checkbox.checked = false;
});
}
</script>
</body>
</html>
The example provides both "Select All" and "Clear All" functionality using the forEach() method after converting HTMLCollection to an array.
HTMLCollection vs NodeList
It's important to understand the difference between HTMLCollection and NodeList when working with DOM collections
| HTMLCollection | NodeList |
|---|---|
| Live collection (updates automatically) | Can be live or static depending on method |
| Contains only HTML elements | Contains all node types (elements, text, comments) |
No built-in forEach() method |
Has built-in forEach() method |
Returned by getElementsByClassName(), getElementsByTagName()
|
Returned by querySelectorAll(), childNodes
|
| Accessible by index and named item | Accessible by index only |
Example HTMLCollection vs NodeList
Following example shows the difference between HTMLCollection and NodeList
<!DOCTYPE html>
<html>
<head>
<title>HTMLCollection vs NodeList</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
<h2>HTMLCollection vs NodeList Comparison</h2>
<div class="demo">Element 1</div>
<div class="demo">Element 2</div>
<div class="demo">Element 3</div>
<div id="output" style="margin-top: 15px; border: 1px solid #ccc; padding: 10px; background: #fff3cd;"></div>
<script>
let output = document.getElementById('output');
// HTMLCollection
let htmlCollection = document.getElementsByClassName('demo');
// NodeList
let nodeList = document.querySelectorAll('.demo');
output.innerHTML = `
HTMLCollection length: ${htmlCollection.length}<br>
NodeList length: ${nodeList.length}<br>
HTMLCollection has forEach: ${typeof htmlCollection.forEach}<br>
NodeList has forEach: ${typeof nodeList.forEach}<br>
`;
</script>
</body>
</html>
The output shows the key differences between HTMLCollection and NodeList
HTMLCollection vs NodeList Comparison Element 1 Element 2 Element 3 HTMLCollection length: 3 NodeList length: 3 HTMLCollection has forEach: undefined NodeList has forEach: function
