Winge
Winge

Reputation: 33

access a single object in a returned collection (jquery)

Okay, if I have a html document that looks a bit like this:

<div class='item'> ... </div>
<div class='item'> ... </div>
<div class='item'> ... </div>
<div class='item'> ... </div>

I know I an iterate over them by doing

$('.item').each

But what if I already know I want to do something with the second one? Is there some sort of syntax similar to:

$('.item')[2]

which is usable as a selector? ie. I'd want to do:

$('.item')[2].css('display','block');

Possible or not? :)

Upvotes: 3

Views: 71

Answers (1)

gnarf
gnarf

Reputation: 106332

Yup, .eq() will restrict the jQuery set to just the one element you want:

$('.item').eq(2).css('display','block');

There is also an :eq() selector that will do the same:

$('.item:eq(2)').css('display','block');

As Andy mentions in the comments, both of these functions use zero-based indexing... Meaning 2 is the third element...

Upvotes: 5

Related Questions