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? 🙂
Yup,
.eq()will restrict the jQuery set to just the one element you want:There is also an
:eq()selector that will do the same:As Andy mentions in the comments, both of these functions use zero-based indexing… Meaning
2is the third element…