Why doesn't the $ .each () variable go through every element?

I have the following markup containing 10 pre elements with an indent class:

 ​<pre class="indent"></pre> <pre class="indent"></pre> <pre class="indent"></pre> <pre class="indent"></pre> <pre class="indent"></pre> <pre class="indent"></pre> <pre class="indent"></pre> <pre class="indent"></pre> <pre class="indent"></pre> <pre class="indent"></pre>​ 

I use the following jQuery .each() function to iterate through each element:

 ​$(function(){ $.each(".indent", function(index){ alert(index); }); });​ 

I expect to see 10 warnings, however I only see 7

- see Fiddle -




However, this works as expected with $(".indent").each() :

 $(function(){ $(".indent").each(function(index){ alert(index); }); });​ 

- see Fiddle -




Looking at the $.each() documentation, I realize that this is the difference:

The $ .each () function does not match the $ (selector) .each (), which is used to iterate over the jQuery object exclusively.

But I do not understand why in this case it does not iterate over all the elements.

Why is this happening?

+53
javascript jquery iteration
Nov 30 '12 at 15:50
source share
3 answers
 $.each(".indent", function(index){ 

does not iterate over the elements of $('.indent') , but over the string ".indent" with a length of 7 characters.

See link




More detailed explanation based on jQuery source code :

jQuery first checks to see if the first obj parameter (here is your string) length :

 var ... length = obj.length, isObj = length === undefined || jQuery.isFunction( obj ); 

Your string having length (and not a function) isObj is false .

In this case, the following code is executed:

 for ( ; i < length; ) { if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { break; } } 

So, given the function f , the following code

 $.each(".indent", f); 

equivalently

 for (var i=0; i<".indent".length; i++) { var letter = ".indent"[i]; f.call(letter, i, letter); } 

(you can write letters with var f = function(i,v){console.log(v)}; or recall one of the subtleties of call with var f = function(){console.log(this)}; )

+144
Nov 30 '12 at 15:51
source share

Iterating over a string, you must pass an object or array to the $.each method:

 $(function(){ $.each($(".indent"), function(index){ alert(index); }); }); 
+38
Nov 30 '12 at 15:52
source share

$, each of which iterates over a dataset. Since you are passing a string containing 7 characters, it will iterate over each char. See Usage Example:

 $.each([52, 97], function(index, value) { alert(index + ': ' + value); }); 
+22
Nov 30 '12 at 15:53
source share



All Articles