Davor Zubak
Davor Zubak

Reputation: 4746

How to get child element by index in Jquery?

<div class="second">
    <div class="selector" id="selFirst"></div>
    <div class="selector" id="selSecond"></div>
    <div></div>
</div>

How to get #selFirst using element index not the ID?

this:

var $selFirst = $(".second:nth-child(1)");
console.log($selFirst);

is returning :

jQuery(div.second)

Upvotes: 81

Views: 140063

Answers (6)

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41767

If you know the child element you're interested in is the first:

 $('.second').children().first();

Or to find by index:

 var index = 0
 $('.second').children().eq(index);

Upvotes: 212

Deepak Kumar
Deepak Kumar

Reputation: 578

There are the following way to select first child

1) $('.second div:first-child')
2) $('.second *:first-child')
3) $('div:first-child', '.second')
4) $('*:first-child', '.second')
5) $('.second div:nth-child(1)')
6) $('.second').children().first()
7) $('.second').children().eq(0)

Upvotes: 22

unaesthetic
unaesthetic

Reputation: 98

Doesn't nth-child return siblings rather than children?

var $selFirst = $(".second:nth-child(1)");

will return the first element with the class '.second'.

var $selFirst = $(".selector:nth-child(1)");

should give you the first sibling of class '.selector'

Upvotes: 2

Raynos
Raynos

Reputation: 169491

var node = document.getElementsByClassName("second")[0].firstElementChild

Disclaimer: Browser compliance on getElementsByClassName and firstElementChild are shaky. DOM-shims fix those problems though.

Upvotes: -6

mbx-mbx
mbx-mbx

Reputation: 1775

$('.second').find('div:first')

Upvotes: 3

Samich
Samich

Reputation: 30155

You can get first element via index selector:

$('div.second div:eq(0)')

Code: http://jsfiddle.net/RX46D/

Upvotes: 7

Related Questions