0

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!

1

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I was searching for hours and then 2 minutes after I posted this, I found it. But since your answer is correct, you get the check. :-)
1

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.

1 Comment

Thanks for taking the time to answer. To my understanding get() gets the element, not an array with the element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.