Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn jQuery each() into regular javascript loop

A couple questions:

  1. Is a regular javascript loop (to loop through a series of elements) faster/more efficient than using jQuery each() ??

  2. If so, what is the best way to write the following code as a regular javascript loop?

$('div').each(function(){ //... })

like image 721
HandiworkNYC.com Avatar asked Aug 24 '12 21:08

HandiworkNYC.com


People also ask

What is the use of jQuery each () function?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

Can we use foreach in jQuery?

Learn how to loop through elements, arrays and objects with jQuery using the $. each() function, jQuery's foreach equivalent. jQuery's foreach equivalent can be very useful for many situations. These examples will get you started and teach you how you can loop through arrays, objects and all kinds of HTML elements.

How do you iterate through an element in jQuery?

The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0.

How do you loop A to Z in JavaScript?

log(String. fromCharCode(65)); So, the value 65 is A, the same way to print B, we need to pass the value of 66 and so on. Therefore, to print A to Z, all we have to do is to pass the value from 65 to 91.


2 Answers

Yes, removing the each() will give you slightly better performance. This is how you could write a for loop for a list of elements.

var divs = $('div');

for(var i = 0; i < divs.length; i++){
    var thisDiv = divs[i]; // element

    var $thisDiv = $(divs[i]); // jquery object

    // do stuff
}
like image 110
Gabe Avatar answered Sep 24 '22 05:09

Gabe


var divs = document.getElementsByTagName('div'),
    l = divs.length, i, cur;

for(i=0; i<l; i++) {
    cur = divs[i];
    // do stuff with cur here
}

Please continue on your path to removing jQuery in the name of efficiency. This code is approximately fifty times faster than the jQuery equivalent.

like image 32
Niet the Dark Absol Avatar answered Sep 26 '22 05:09

Niet the Dark Absol