How to turn jQuery each () into a regular javascript loop

A few questions:

  • Is a regular javascript loop (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(){ //... })

+8
javascript jquery loops
source share
4 answers

Yes, removing each() will give you a slightly better performance. So you can write a for loop for a list of items.

 var divs = $('div'); for(var i = 0; i < divs.length; i++){ var thisDiv = divs[i]; // element var $thisDiv = $(divs[i]); // jquery object // do stuff } 
+9
source share
 var divs = document.getElementsByTagName('div'), l = divs.length, i, cur; for(i=0; i<l; i++) { cur = divs[i]; // do stuff with cur here } 

Continue on to remove jQuery in the name of efficiency. This code is about fifty times faster than the jQuery equivalent.

+5
source share

To answer the second question, because of the first answer to it;

I was also interested in this, and I decided to compare the two to find the difference using the Gabe example. The answer is that, if desired, the jQuery object is the end result:

They do exactly the same thing.

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

Firefox actually finds the jQuery version faster, apparently.

+1
source share

Instead of using jquery .each()

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

You can use document.querySelectorAll() and then convert the HTMLCollection to a JavaScript array. Then you can map an array of elements.

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

All Articles