Take matrix size with EQ() - Jquery

Asked

Viewed 497 times

3

I’m with a html which has five elements div.

I would like you to help me somehow to make a Get the size of this matrix in Jquery.

Ex: with the function eq(), consige take a page element, referenced by matrix. If I use the following code $( "body" ).find( "div" ).eq( 2 ).css( "background-color","blue");, the third div the matrix will have the background in blue.

How to get the total value of this matrix?

  • 3

    Have you tried $( "body" ).find( "div" ).length?

  • By "total value" it is unclear whether you want the number of Divs, or an array with all Divs inside. Anyway, my answer points the way.

  • 1

    @Sergio thanks, Solved the problem!

  • @Franckcosta, great! I also left an answer below. You can mark as correct if that was the solution you were looking for.

3 answers

5


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

var matriz = $( "body" ).find( "div" ).length;
  • 1

    this is how I used and worked, I appreciate the help!

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 property length indicating how many items are inside).

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

var arrayDeDivs = $( "body" ).find( "div" ).get();

3

If your goal is to apply some style to the latter div found inside the body, can do this using jquery selector :last:

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

or

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

I just found out that eq can be used with negative values, to pick up 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: Nor :last nor :eq are CSS selectors, only work in jQuery.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.