Array Iteration using HTML Collection Loop
Using JavaScript, we've got a few ways to roam through an of elements, like those snatched up by or . Here's the skinny:
- Use a for/of Loop
- Utilize Array.from() Method
- Employ a Normal for Loop
For/of Loop, here's the lowdown!
The for/of loop is like the cool kid on the block, used to run 'n' gun over values in an iterable object. That object can be an array, a string, a NodeList, or an HTMLCollection. The loop's syntax rocks and rolls much like the not-so-cool-anymore for/in loop. Just make sure your object is iterable to get with this loop!
Syntax
Let's say you've got an HTMLCollection of paragraphs,
elements, and you wanna loop over them. You'd wanna avoid logging the collection[i] and instead go straight for i, but you're probably gonna end up with an undefined result.
Array.from() Method, have a gander!
The Array.from() method is a handy chap for creating an array from an array-like or iterable object. An HTMLCollection is passed to this method, where it's then turned into an array. You can now take advantage of to breeze through the elements like a Zoomer rabbit and log 'em all to the console.
Syntax
Similar to what we experienced earlier, let's turn our HTMLCollection of
elements into an array with , then use to log every paragraph to the console.
Normal for Loop, it ain't dead yet!
You can proceed to iterate through the elements with a traditional for loop. The number of elements in the collection can be easily snagged by checking the property. Toss a for loop into the mix, and you can access each of the elements using square brackets with their respective index.
Syntax
Here, we're employing a for loop to log every element in an HTMLCollection of
elements, focusing on just two paragraphs.
Next Up, let's dive into the nitty-gritty of the TableRow cells Collection in HTML!
- HTML-Misc
- HTML-Questions
- In the realm of JavaScript, arrays and graphs can be utilized to structure and analyze data retrieved from HTML elements.
- When dealing with an HTMLCollection, you can create an array using the Array.from() method and then apply graph algorithms to process the data, enabling data visualization through graph representations.