How to get child element by index in Jquery?
JavascriptJqueryJquery UiJquery SelectorsJavascript Problem Overview
<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)
Javascript Solutions
Solution 1 - Javascript
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);
Solution 2 - Javascript
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)
Solution 3 - Javascript
You can get first element via index selector:
$('div.second div:eq(0)')
Solution 4 - Javascript
$('.second').find('div:first')
Solution 5 - Javascript
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'
Solution 6 - Javascript
var node = document.getElementsByClassName("second")[0].firstElementChild
Disclaimer: Browser compliance on getElementsByClassName
and firstElementChild
are shaky. DOM-shims fix those problems though.