redconservatory
redconservatory

Reputation: 21934

jQuery find an element by its index

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

Answers (7)

Timothy Aaron
Timothy Aaron

Reputation: 3078

$('#container').children().eq(2);

Upvotes: 0

Rob W
Rob W

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

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79840

You can use :eq selector like below,

   $('#container div:eq(2)') //will return you div with item 2

Upvotes: 0

mreyeros
mreyeros

Reputation: 4379

Good morning you could use the nth-child selector:

 var item = $('#container div:nth-child(2)');

Upvotes: 0

ShankarSangoli
ShankarSangoli

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

Mathias Bynens
Mathias Bynens

Reputation: 149734

$('#container').children().eq(1);

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337701

Try:

$("#container div").eq(1) // zero-based, so will select 'item 2'

Upvotes: 0

Related Questions