Get array size with EQ () - Jquery

3

I have a html that has five elements div .

I would like some help to get a get of the size of this array in Jquery.

Ex: With the function eq() , you get an element of the page, referenced by array. If I use the following code $( "body" ).find( "div" ).eq( 2 ).css( "background-color","blue"); , the third div of the array will have the background in blue.

How do I get the total value of this array?

    
asked by anonymous 11.04.2014 / 19:07

3 answers

5

If you want to know how many elements / objects this array has, you can use .length that it will give you the number of elements in the jQuery object.

var matriz = $( "body" ).find( "div" ).length;
    
11.04.2014 / 19:19
4

What jQuery returns to $( "body" ).find( "div" ) is a "jQuery object", which is very similar to an array. In many ways, it can be treated as if it were one (for example, it has% ownership as% indicating how many items are inside).

But if you want a pure array, you can simply use:

var arrayDeDivs = $( "body" ).find( "div" ).get();
    
11.04.2014 / 19:12
3

If your goal is to apply some style to the last div found within body , you can do this by using the jquery :last :

$( "body div:last" ).css( "background-color","blue");

or

$( "body div" ).last().css( "background-color","blue");

I just discovered that eq can be used with negative values, to get elements from the last down:

$( "body div" ).eq(-2); // pega o penúltimo
$( "body div" ).eq(-1); // pega o último

or

$( "body div:eq(-1)" ); // pega o último

Note: Neither :last nor :eq are CSS selectors, they only work in jQuery.

    
11.04.2014 / 19:20