A couple questions:
Is a regular javascript loop (to loop through a series of elements) faster/more efficient than using jQuery each()
??
If so, what is the best way to write the following code as a regular javascript loop?
$('div').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.
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.
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.
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.
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With