Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Each() as a For statement?

I have a jQuery.each() function that I would like to turn into a FOR statement.

I was wondering how I can turn

     jQuery('.myclass').each(function() {
       //do stuff
     }

into a

   for ( var i=0; i<.myclass.length; i++) {
    //do stuff
   }

?

like image 990
ssDille Avatar asked Feb 24 '23 06:02

ssDille


1 Answers

jQuery objects are array-like. They have a length property and they support accessing elements by using numeric indexes with []. So you just index directly into the resulting object:

var myclass = jQuery('.myclass');

for ( var i=0; i<myclass.length; i++) {
    // use myclass[i] here
}

This information isn't especially flagged up in the API docs, but you can find it in the documentation of the get function. The bracket notation largely replaces use of the get function except for its handling of negative index values (which are used to index relative to the end of the collection; negative indexes are only supported via get, not via []).

like image 142
T.J. Crowder Avatar answered Mar 04 '23 04:03

T.J. Crowder