Js html collection foreach

clubmate.fi

The forEach loop for beginners, and how to use it with a nodeLists, and HTMLCollections.

So the forEach loop loops and array and gives access to the current item through a callback function. It doesn’t return anything.

var normalArray = ['foo', 'bar', 'baz', 'fooz'] normalArray.forEach(function (currentValue, index, array)  console.log(currentValue + ' - ' + index + ' - ' + array) >)

currentValue The current element of the array being processed. index The index of the currentValue . array The original array the loop was call upon.

Looping HTMLCollection or a nodeList with forEach

When querying elements on the page, the resulting collection is no an array, but:

These return not arrays of nodes but nodeLists, which are freaky weird things — Douglas Crockford

Here’s our super simple HTML that we’re going to be working with:

div class="module">div> div class="module">div> div class="module">div>

HTMLCollection or a nodeList are not arrays, per se, they’re «array-like objects», and we can’t use forEach right out the box. But what we can do is to call the Array s forEach method directly, like so:

// Grab the wanted elements var htmlCollection = document.getElementsByClassName('module') Array.prototype.forEach.call(htmlCollection, function (element)  console.log(element.tagName) >)

The Array.prototype can be truncated to a pair of brackets [] , like so:

;[].forEach.call(htmlCollection, function (element)  console.log(element.tagName) >)

Or you can spread the nodeList or the HtmlCollection and then use it like any other array:

var htmlCollection = [. document.querySelectorAll('.module')] htmlCollection.forEach(function (element)  console.log(element.tagName, 'foo') >)

Just as a reminder that the good old for loop works great also:

for (var i = 0; htmlCollection.length  i; i++)  console.log(htmlCollection[i].tagname) >

There are things forEach can’t do. The two words «for» and «Each» are taken very literally, you’re about to iterate every single element in the array, break or continue can’t be used. Here’s a non working example:

;['foo', 'bar', 'baz'].forEach(function (element, index)  if (index > 3)  // Does not work break // Likewise for: // continue > console.log('Current ' + element + ', Index ' + index) >)

You get an error: Uncaught SyntaxError: Illegal break statement .

Or just use a for loop if you need to break . I have a post about looping and manipulating objects that has a lot of good stuff related to this, have look.

Источник

How to Loop Through an HTMLCollection

If you’ve ever written a frontend application in JavaScript, you’ve probably run into HTMLCollections. I recently deployed Plant Flashcards, a full-stack application where you can learn about plant facts and test your knowledge. I used a vanilla JavaScript for the frontend and a homegrown Rails API for the backend! Interacting with JSON objects and trying to manipulate elements on the DOM made me realize that HTMLCollections were very different from plain ole, regular Arrays. HTMLCollections are array-like objects that return HTML elements on the DOM. Unlike regular Arrays, they’re “live” objects, so they’ll change automatically depending on the contents of the DOM.

Let’s dive in

Here’s an example of a variable that will return an HTMLCollection. In this line of code, we’re pulling all the elements from the document object that have the class name plant . We’re then assigning it to a variable called plantsArray .

let plantsArray = document.getElementsByClassName("plant") 

Example of an HTMLCollection

And here’s what plantsArray might look like when logged to the console:

The difference between HTMLCollections and Arrays

Out of all the CRUD (Create, Read, Update, Delete) operations, HTMLCollections are mainly used for reading elements. They’re not meant for DOM manipulation because they’re live objects. Arrays, on the other hand, can be easily mutated. HTMLCollections also have different built-in properties and methods than Arrays. See what happens when we try to access the individual elements in an HTMLCollection like we would with an Array.

plantsArray.forEach((plant) =>  console.log(plant) >) => TypeError: plantsArray.forEach is not a function 

Trying to run a .forEach() method on plantsArray gives us a TypeError. HTMLCollections may look like Arrays and are also technically a list of objects, but they are fundamentally different.

How to loop through an HTMLCollection

1) If we want to be able to use the .forEach() method, we can turn the HTMLCollection into an Array, then call the method on it.

Array.from(plantsArray).forEach((plant) =>  console.log(plant.name) >) => "Monstera", "ZZ Plant", "Snake Plant" 
for (plant of plantsArray)  console.log(plant.name) > => "Monstera", "ZZ Plant", "Snake Plant" 
for (i = 0; i  plantsArray.length; i++)  console.log(plantsArray[i].name) > => "Monstera", "ZZ Plant", "Snake Plant" 

Источник

How to Iterate through a HTMLCollection or NodeList in JavaScript DOM

How to Iterate through a HTMLCollection or NodeList in JavaScript DOM

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.

let liItems = document.querySelectorAll('li'); liItems.forEach((liItem) => < console.log(liItem.textContent) >)

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.

let liItems = document.getElementById('parentElement').children; let liItemsArray = Array.from(liItems) liItemsArray.forEach((liItem) => < console.log(liItem.textContent) >)

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

let liItems = document.getElementById('parentElement').children; for (liItem of liItems)

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

Источник

HTMLCollection for Loop

The HTML collection is an array of HTML elements. We can access every element of the collection using its index. Also, we can iterate through the array of HTML collections and get all HTML elements of the collection one by one.

Sometimes, we require to use for loop to iterate through the collection of all HTML elements. For example, we have created a group of checkboxes, and when the user presses the clear button, we require to clear all checkboxes. We can access all checkboxes in the HTML collection, iterate through it, and uncheck every checkbox.

In this tutorial, we will learn about different types of for loops to iterate through HTML collections.

Use the for loop

We can access the multiple HTML elements in JavaScript and use them for a loop to iterate through an array of numbers or strings.

We can initialize the index variable in the for loop and access the collection element using the index in every iteration.

Syntax

Users can follow the syntax below to use the for loop to iterate through HTML collections.

In the above syntax, ‘i’ is the index initialized with 0, and we are iterating through collections until the index is less than the length of collections.

Example 1

In the example below, we have created the 5 div elements. Also, we have assigned the same class names to every div. In JavaScript, we access all div elements by class name.

So, allDivs is a HTML collection of div elmeents. After that, we used the innerHTML property of div elements to get its content, which showed up in the output.

  

Using the for loop to iterate through the HTML collections.

Div 1
Div 2
Div 3
Div 4
Div 5

Use the for-of loop

The for-of loop is also used to iterate through the collections or array elements, giving a single array element in the array order. On the ith iteration, it returns the element from the ith index of the array.

Syntax

Users can follow the syntax below to use the for-of loop to iterate through the HTML collections.

for (let element of collection) < // element is the collection’s element >

In the above syntax, a collection is an HTML collection containing multiple HTML elements.

Example 2

In the example below, we have created the HTML’s five

elements. In JavaScript, we access the

elements using the class name. Also, we used the for-of loop to iterate through the collections.

Also, we have access to the inner html of every

element while iterating through the HTML collection.

  

Using the for-of loop to iterate through the HTML collections.

Car

Bike

Truck

Cycle

Tempo

Use the forEach() method

The forEach() method also iterates through every element of the collection. We need to take the collection as a reference, and the forEach() method calls the callback function for every collection element.

We need to pass the callback function as a parameter of the forEach() method, which also takes the collection element as a parameter, which we can use inside the callback function.

Syntax

Users can follow the syntax below to use the forEach() method to iterate through the HTML collections.

allCheckboxes.forEach((checkbox) => < // this is the body of the callback function >)

In the above syntax, allCheckboxes is a collection of HTML elements.

Example 3

In the example below, we have created a group of multiple checkboxes. After that, we accessed all checkboxes in JavaScript. Whenever the user presses the button, we use the forEach() method to iterate through all checkboxes, and uncheck all checkboxes using JavaScript.

  

Using the forEach() method to iterate through the HTML collections.



We learned to loop through the HTML collections using for loop in JavaScript. We have used the three variants of the for loop to iterate through the collection. The forEach() loop is faster than the normal for loop and for-of loop and performs better.

Источник

Читайте также:  Php zip get all files
Оцените статью