Reputation: 21934
If I have a selection
<div id="container">
<div>item 1</div>
<div>item 2</div>
<div>item 3</div>
<div>item 4</div>
</div>
How can I select a div by it's index?
For example, I'd like to select item 2...by using index = 1, not by 'div' or text contains "item 2"
Upvotes: 2
Views: 5791
Reputation: 349212
Either of these:
.index
- This is the getter. Get the index of a given element, and apply logic, based on it..eq
, :eq
or .slice
- These can be used to get an element from a given jQuery collection:nth-child
- Select an element which is the nth child (!!) element, respective to the parent.In your case, eq
or :nth-child
are suitable. Eg:
var item1 = $('#container > :nth-child(1)'); // parent > child (=first child)
var item2 = $('#container').children().eq(1); // Zero-based indexes
Upvotes: 5
Reputation: 79840
You can use :eq selector like below,
$('#container div:eq(2)') //will return you div with item 2
Upvotes: 0
Reputation: 4379
Good morning you could use the nth-child selector:
var item = $('#container div:nth-child(2)');
Upvotes: 0
Reputation: 69915
Use eq()
method.
$("#container > div").eq(1)
You can even use :eq(1)
pseudo selector.
$("#container > div:eq(1)")
.eq(index)
reduces the set of matched elements to the one at the specified index.
:eq(index)
selects the element at index n within the matched set.
Upvotes: 1
Reputation: 337701
Try:
$("#container div").eq(1) // zero-based, so will select 'item 2'
Upvotes: 0