Graham
Graham

Reputation: 8171

how to select (in jquery) the nth child div when other child elements also exist

I have something like the following html:

<div id="foo">
  <div>...</div>
  <p>...</p>
  <div>...</div>
  <p>...</p>
  <hr />
  <div>...</div>
  <div>...</div>
</div>

In between each sub div of "foo" there are zero or more other elements. I want to be able to select the nth sub div of foo.

nth-child includes the other elements. For example:

$("#foo:nth-child(2)")

gives me the first p tag instead of the second div.

Upvotes: 0

Views: 58

Answers (2)

Amit Kumar
Amit Kumar

Reputation: 5962

your jquery would be

$("#foo").find('div:eq(1)')

for more specific, if child contain another div too, then you will have to use child selector.

$("#foo > div:eq(1)")

DEMO

Upvotes: 2

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

Try to use :nth-of-type(n) here,

$("#foo > div:nth-of-type(2)")

DEMO

Upvotes: 2

Related Questions