How to get child element by index in Jquery?

JavascriptJqueryJquery UiJquery Selectors

Javascript 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)')

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

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavor ZubakView Question on Stackoverflow
Solution 1 - JavascriptRich O'KellyView Answer on Stackoverflow
Solution 2 - JavascriptDeepak KumarView Answer on Stackoverflow
Solution 3 - JavascriptSamichView Answer on Stackoverflow
Solution 4 - Javascriptmbx-mbxView Answer on Stackoverflow
Solution 5 - JavascriptunaestheticView Answer on Stackoverflow
Solution 6 - JavascriptRaynosView Answer on Stackoverflow