Reputation: 1299
With jQuery I can do
$('#some_id').find('div').first()
or
$('#some_id').find('div').last()
and get an answer like
[<div>something</div>]
If I do
$('#some_id').find('div')[3]
I get answer like
<div>something</div>
How do I specify an index in array and get an array just with that object?
I would love to do something like
$('#some_id').find('div').somefunc(3)
and get
[<div>something</div>]
I know there is slice(), but I feel like there is some simpler function that I have over looked in my hours of searching.
I know there is :nth-child() but again, it feels like there is some other function that I can call the way I call first() or last().
I am trying to chain some functions together to have one line that does what I need.
If there is not other ways, then I guess that is fine. I just wanted to make sure.
Thanks!
Upvotes: 0
Views: 62
Reputation: 7367
You can also use .get(index)
$($('#some_id').find('div').get(3)); // jQuery obj
or
[$('#some_id').find('div').get(3)]; // Array
The .get() method grants access to the DOM nodes underlying each jQuery object. If the value of index is out of bounds — less than the negative number of elements or equal to or greater than the number of elements — it returns undefined.
Upvotes: 1
Reputation: 779
You can use .eq():
$('#some_id').find('div').eq(3) // This will return the fourth div inside #some_id
Since .eq()
is 0-based index, if you want to get the third div you need to use:
$('#some_id').find('div').eq(2)
Upvotes: 4