jQuery each is one of the better-used functions in jQuery so I think it’s great to understand what you can do with it.
The jQuery each function is used to loop over data the accessible way to think of it is that it’s similar to a foreach loop in other languages. So you can use it to loop over a number of DOM objects from the same selectors for a case if you want to add a target=”_blank” to all links on the page then you will select all associations and loop through each of them to add a target=”_blank”.
Let us investigate how this works. Earliest in order we get all the anchor links on the page by using the following selector.
Next we adoption each function to loop through all the links.
When you’re central the each function you can access the current element it is the loop through by using this keyword, but this article will not be a jQuery object and therefore if it’s a DOM aspect you will not be able to use any jury functions on it. The solution to this complication is to wrap this inside a jQuery object defined.
When we have the current bashed element inside a jQuery object we can then add a new aspect to the link by using the attr function.
Get The Current Index Of The Loop
In the above example, you’ll attend the I inside the function() parameters. This variable is colonized with the current index of the each to see this alive have 10 links on the page.
Then output the current index by watchful this to the user.
Loop Through Arrays
In the above example, you saw how you can select DOM elements and loop through them but you can also use it to curve through arrays of data and get both the indicator and the value of the area inside the array.
In the console, it will output the following.
“0 orange” “1 apple” “2 banana” “3 grapes” “4 kiwi”
Loop Through Objects
What if you’re using objects to store data and not batch, each function will take care of that the same way as you can notice in the following code.
The output of looping over the object is below.
“1 orange” “2 apple” “3 banana” “4 grapes” “5 kiwi”