7 Ways To Avoid jQuery .each() Method With An Equivalent JavaScript .forEach() Method

This tutorial explains the 7 important ways to work with the JavaScript .forEach() method so that you can replace your jQuery .each() method's code with it.

7 Ways To Avoid jQuery .each() Method With An Equivalent JavaScript .forEach() Method
 
JavaScript introduced its 6th edition in June 2015. The 6th edition of JavaScript is popularly known as ES6 or ECMAScript. ES6 gave JavaScript some of the new, modern and powerful methods, and one such method is .forEach(). This method is used to loop through all the elements of an array and at the same time execute a provided function for every array’s element.

Earlier developers (including me) were using the jQuery Each method - .each(), for doing the process of looping over the array elements. But now all these works can be simply done by the JavaScript’s .forEach() method. So I present you with the 7 ways to avoid jQuery Each method with an equivalent JavaScript .forEach() method on your website.

Syntax of JavaScript .forEach()

The syntax is fairly simple:

  1. array.forEach(function(currentValue, index, arr), thisValue)  

The 1st parameter is a ‘Required’ one and is a callback function that runs for each element of the array. This callback function has 3 parameters - function (currentValue, index, arr)

  1. currentValue – ‘Required’, specifies the value of the current element.
  2. index – ‘Optional’, specifies the index of the current element in the array
  3. arr – ‘Optional’, specifies the array object the current element belongs to.
The thisValue is the 2nd parameter of the .forEach() method. It is an ‘Optional’ parameter which specifies a value to be passed to the function to be used as its "this" value. If this parameter is empty, the value "undefined" will be passed as its "this" value. This parameter is hardly used in the .forEach() method so simply avoid it all the time.

Now let us start with the 7 way of using the .forEach() method.

First way – Looping through an Array

You can loop through all the elements of an array with the .forEach() method. In the below code I am showing the index and value of each element of the array in the console.

  1. var names = ["yogi""alia""john""cindy""david"];  
  2. names.forEach(myFunction);  
  3.   
  4. function myFunction(currentValue, index) {  
  5.     console.log("Array Current Index is: " + index + " :: Value is: " + currentValue);  
  6. }  

On executing this code you will get the following output on the console,

7 Ways To Avoid jQuery .each() Method With An Equivalent JavaScript .forEach() Method 

Second way – Looping through DOM elements

Here I will get all the anchors given in a web page. I will then loop through all of these anchors and show their contents.

  1. var links = document.getElementsByTagName("a");  
  2. var linksArr = Array.from(links);  
  3. linksArr.forEach(myFunction);  
  4.   
  5. function myFunction(currentValue) {  
  6.     console.log(currentValue);  
  7. }  

I first get these anchors by using the getElementsByTagName() function and then converting its result to an array by using the Array.from() method.

Run the above code in the console of any web page and you will see the result as shown below,

7 Ways To Avoid jQuery .each() Method With An Equivalent JavaScript .forEach() Method 

If you want to do the same thing with the jQuery Each method then the code will be,

  1. $("a").each(function(index,value) {  
  2.     console.log($(this).attr("href"));  
  3. });  

Third way – Extracting values from JSON

Suppose you have a JSON which contains the City names. I want to extract all the city names from it. In that case I can use JavaScript .forEach() code like this,

  1. var json = [{ "City""Washington DC" }, { "City""Islamabad" }, { "City""Beijing" }, { "City""Tokyo" }];  
  2.   
  3. json.forEach(function (currentValue, index) {  
  4.     console.log(currentValue.City)  
  5. });  
The output produced in this case is shown below,
 
7 Ways To Avoid jQuery .each() Method With An Equivalent JavaScript .forEach() Method 

Fourth way – Extracting values from XML

You can also extract values from an XML using the .forEach() method. Check the below code,

  1. var xml = "<cities><city>Washington DC</city><city>Islamabad</city><city>Beijing</city><city>Tokyo</city></cities>";  
  2. parser = new DOMParser();  
  3. xmlDoc = parser.parseFromString(xml, "text/xml");  
  4.   
  5. Array.from(xmlDoc.getElementsByTagName("city")).forEach(function (currentValue, index, arr) {  
  6.     console.log(currentValue.textContent)  
  7. });  

Explanation

Here the variable called ‘xml’ contains the XML. I first parsed the text string contained in ‘xml’ variable into an XML DOM object, which is done by the below 2 lines,
  1. parser = new DOMParser();  
  2. xmlDoc = parser.parseFromString(xml, "text/xml");  

Next, I fetched all anchors from this XML DOM object (which is ‘xmlDoc’) and converted it into an array,

  1. Array.from(xmlDoc.getElementsByTagName("city"))  

Finally I looped through this array using the .forEach() method and extracted the city name from it.

7 Ways To Avoid jQuery .each() Method With An Equivalent JavaScript .forEach() Method

Fifth way – Looping through DOM elements with a certain CSS class

In this example I get all the elements having “w3-example” class by using the getElementsByClassName() method. I then converted it to an array and used .forEach() for looping through all the elements in the array. See the below code,

  1. var elements = document.getElementsByClassName("w3-example");  
  2. var elementsArr = Array.from(elements);  
  3. elementsArr.forEach(myFunction);  
  4.   
  5. function myFunction(currentValue, index) {  
  6.     console.log(currentValue);  
  7. }  

I ran the above code in the console window of w3schools site and got 4 elements having the w3-example class. Check the below image:

7 Ways To Avoid jQuery .each() Method With An Equivalent JavaScript .forEach() Method

Sixth way – Animations with JavaScript .forEach()

It may feel impossible to do animations with the .forEach() method but there is a way. Let me show you.

Here I will make 3 divs to expand and collapse, in a widthwise direction, by showing a good animation effect.

I have 3 div elements with CSS class called ‘block’, and each having a width of 75pixels.

  1. <div class="animateDiv">  
  2.     <div class="block" style="width:75px"></div>  
  3.     <div class="block" style="width:75px"></div>  
  4.     <div class="block" style="width:75px"></div>  
  5. </div>  

  6. <button onclick="CallForEach()">Click</button>  
There is also a button on whose click event I will change the width of these 3 divs to 0 pixels with animation effect.

First add 2 CSS classes in your page head,

  1. <style>  
  2. .animateDiv {  
  3.     display: inline-block;  
  4.     width: 100%;  
  5.     padding: 50px;  
  6.     background: #000;  
  7. }  
  8.   
  9. .block {  
  10.     height: 75px;  
  11.     border: solid 1px #FFF;  
  12.     float: left;  
  13.     margin-right: 25px;  
  14.     transition: all .3s ease-in-out;  
  15. }  
  16. </style>  

Notice the transition property transition - all .3s ease-in-out; which tells that whenever any property of the .block class changes then the change will be done with ease-in-out effect in .3seconds time.

Now add the CallForEach() function which will be called in the button click event.

  1. function CallForEach() {  
  2.     var elements = document.querySelectorAll(".block");  
  3.     elements.forEach((a, b) => {  
  4.         setTimeout(function () {  
  5.             if (a.style.width == "75px")  
  6.                 a.style.width = "0px";  
  7.             else  
  8.                 a.style.width = "75px";  
  9.         }, b * 2000);  
  10.     });  
  11. }   

Explanation

Let me explain what this function does. First it gets all the elements having the .block CSS class which in my case is the 3 divs. I do this by using the JavaScript’s querySelectorAll() method, and this method gives all these elements in an array form.

Next, I loop through the elements array (that contains the 3 divs) by using the .forEach() method like this:

  1. elements.forEach((a, b) => {  
  2. //…  
  3. });  

I used the lambda expression to define my callback function. The lambda expression contains 2 parameters (a,b), which are for the currentValue and Index of the current element of the array.

Now inside the .forEach() method I am using the .setTimout() function of JavaScript.

Reference - JavaScript setTimout() Method

  1. setTimeout(function () {  
  2.     if (a.style.width == "75px")  
  3.         a.style.width = "0px";  
  4.     else  
  5.         a.style.width = "75px";  
  6. }, b * 2000);  

I do a very interesting thing, by delaying the execution of the codes inside the .setTimout() function to run at a delay of 2 seconds time. I do this by providing a value of b*2000 for the time delay parameter. Remember b is the index of the current element of the array.

So that means the codes inside the .setTimeout() function will run at,

  • 0 seconds for the first element since 0*2000=0 second.
  • 2 seconds for the first element since 1*2000=2 seconds.
  • 4 seconds for the first element since 2*2000=4 seconds.
And what I do inside the .setTimout() function is,
  1. if (a.style.width == "75px")  
  2.     a.style.width = "0px";    
  3. else  
  4.     a.style.width = "75px";  

I am checking if the width of the div is 75px so in that case simply make it to 0px. Else if the width of the div is not 75px i.e 0px, then make it to 75pixels. So with these codes, the 3 divs will expand and collapse, in width wise direction with a good animation effect.

Run these codes on your web page and click the button. You will see the 3 divs collapse one by one. Now click the button once more and this time the 3 divs expand one by one with animations.

See this animation in the below video,
 
7 Ways To Avoid jQuery .each() Method With An Equivalent JavaScript .forEach() Method 

Seventh way – Multiplying by JavaScript .forEach()

In this last way to use the .forEach() method, I will find out the multiplication of all the number of an array. See the below code:

  1. var total = 1;  
  2. var numbers = [1, 2, 3, 4, 5];  
  3. numbers.forEach(myFunction);  
  4.   
  5. function myFunction(currentValue, index) {  
  6.     total *= currentValue;  
  7. }  
  8. console.log(total);  

I defined a variable called total with a value of 1. In this variable, the multiplication of all the numbers will be kept.

Inside the .forEach() method I have - total *= currentValue;, and that gives me the multiplication of all the elements of the array.

When you run this code you will get a value of 120 in the console window.

Conclusion

The JavaScript .forEach() method is such a valuable method and you can use it to make your code much shorter and smarter. I hoped you enjoyed learning these 7 ways of using this powerful method.

Do let me know about it in the below comments section. Thank you!