Accessing a single object in a returned collection (jquery)

Well, if I have an html document that looks something like this:

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

I know that I iterate over them, performing

$('.item').each

But what if I already know that I want to do something with the second? Is there any syntax similar to:

$('.item')[2]

which can be used as a selector? i.e. I would like to:

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

Maybe or not? :)

+3
source share
1 answer

Yup, will .eq()limit the jQuery set to only one desired element:

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

There is also :eq()one 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 ... Value 2is the third element ...

+5
source

Source: https://habr.com/ru/post/1762906/


All Articles