Reputation: 4746
<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
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
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
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
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
Reputation: 30155
You can get first element via index selector:
$('div.second div:eq(0)')
Code: http://jsfiddle.net/RX46D/
Upvotes: 7