[ACCEPTED]-How to turn jQuery each() into regular javascript loop-jquery

Accepted answer
Score: 14

Yes, removing the each() will give you slightly 2 better performance. This is how you could 1 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
}
Score: 5
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 3 jQuery in the name of efficiency. This code 2 is approximately fifty times faster than 1 the jQuery equivalent.

Score: 1

To answer your second question, due to the 7 first already being answered;

I was also 6 interested in this, and I decided to benchmark 5 the two to find the difference using Gabe's 4 example. The answer is, in circumstances 3 of wanting a jQuery object as the final 2 result:

They perform exactly the same.

http://jsperf.com/jquery-each-vs-native-selectors

Firefox 1 actually finds the jQuery version faster, apparently.

Score: 1

Instead of using jquery .each()

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

You can use document.querySelectorAll(), then 3 convert the HTMLCollection into a JavaScript 2 array. Then you can map over the array of 1 elements.

 const elems = document.querySelectorAll('.my-elements')
 const $elems = [].slice.call(elems)
 $elems.map( (elem) => { console.log(elem) })

More Related questions