Thursday, March 31, 2011

Loading all objects with class into an array using jQuery

Hi,

I have a bunch of div's on my page with class testClass.

I want to load them into an array and then check the array's size.

But its not working?

myArray = $('testClass');

alert(myArray.count);

What's wrong?

From stackoverflow
  • The code that you have provided returns an iterable jQuery object, but not an array. Also, you have made a mistake in your class selector.

    For check the size of that jQuery object, you can use:

    var $j_object = $(".testClass");
    alert($j_object.size());
    

    To loop over that object, you can use the each() function:

    var $j_object = $(".testClass");
    $j_object.each( function(i) { doSomethingHere(); } );
    

    Check the jQuery documentation for more information on how to use each().

    One other note. If you want to do something with the dom object within the each function, you can refer to 'this'. To get the jQuery object from the dom object, you can use $(this).

    Also, the $ sign is completely optional, but can help to distinguish between jQuery objects and other variables, such as those that denote dom elements.

    Paolo Bergantino : instead of .size(), jQuery recommends you use .length, so $('.testClass').length will give you the amount of elements with a class of "testClass" in the document.
  • You have:

    myArray = $('testClass');
    alert(myArray.count);
    

    You want:

    myArray = $('.testClass');
    alert(myArray.length);
    

    Notice, first, the . for testClass. Then, myArray is a JavaScript object, so you have access to the length key.

  • You can do this without using an array:

    $('.testClass').length
    

    That's all.

0 comments:

Post a Comment