Browsers returns either a HTMLCollection or a NodeList based on the method we use. For example the querySelectorAll method of the document object returns a NodeList while getElementsByClassName returns a HTMLCollection. Similarly the children property of an element returns a HTMLCollection and childNodes property returns a NodeList.
The HTMLCollection and NodeList are iterables in the DOM. That means they are not Arrays but they are iterable objects. They both contain a length property similar to arrays in JavaScript.
Unlike HTMLCollection object, the NodeList object also contains a forEach method, so we can use the forEach method on a NodeList similar to the way we use on arrays.
example:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="index.js" defer></script>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</body>
</html>
JS:
let liItems = document.querySelectorAll('li');
liItems.forEach((liItem) => {
console.log(liItem.textContent)
})
Output:
1
2
3
4
5
If we try to do the same thing with HTMLCollection we get an error like forEach is not a function since HTMLCollection will not have built-in forEach method implemented on it.
Looping through HTMLCollection or NodeList:
To iterate through these objects, we can convert them into pure Arrays by using the from method of Arrays which accepts an iterable as its argument.
example:
HTML:
<ul id="parentElement">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
JS:
let liItems = document.getElementById('parentElement').children;
let liItemsArray = Array.from(liItems)
liItemsArray.forEach((liItem) => {
console.log(liItem.textContent)
})
Output:
1
2
3
Similar to this, we can also pass a NodeList to the from method of the Array object.
By Using for..of
We can use the powerful for..of directly on the HTMLCollection or NodeList
example:
let liItems = document.getElementById('parentElement').children;
for (liItem of liItems) {
console.log(liItem.textContent)
}
By using traditional for loop
We can access individual items from an HTMLCollection or NodeList by using array notation ([]). So, we can use the traditional for loop to access the items from the collection like this
let liItems = document.getElementById('parentElement').children;
for (let i = 0; i < liItems.length; i++) {
console.log(liItems[i].textContent)
}
Leave A Comment