How to use the for/of loop In HTML
The for/of loop is used to loop over values of an iterable object. This includes arrays, strings, nodeLists, and HTMLCollections. The syntax of this loop is similar to the for/in the loop. The object must be iterable to be used with this loop.
Syntax:
for (item of iterable) {
// code to be executed
}
Example: In this example, we will the implementation of the above approach with an example.
html
<!DOCTYPE html> < html lang = "en" > < head > < title >HTML Collection for Loop</ title > </ head > < body > < h1 style = "color: green" >w3wiki</ h1 > < b >For loop for HTMLCollection elements</ b > < p >This is paragraph 1.</ p > < p >This is paragraph 2.</ p > < script type = "text/javascript" > // get a HTMLCollection of elements in the page let collection = document.getElementsByTagName("p"); // regular for loop for (let i of collection) { console.log(collection[i]); } </ script > </ body > </ html > |
Output:
HTML Collection for Loop
It is not recommended to use a for/in loop to loop through an HTMLCollection because this type of loop is used for iterating through properties of an object. The HTML Collection contains other properties that may be returned along with the required elements. There are 3 methods that can be used to properly loop through an HTMLCollection.
Table of Content
- Using the for/of loop.
- Using the Array.from() method
- Using a normal for loop.