How to get child 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 an element index, not an identifier?

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

returns:

 jQuery(div.second) 
+50
javascript jquery jquery-ui jquery-selectors
Jan 19 '12 at 13:19
source share
6 answers

If you know the child that interests you, this is the first:

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

Or find by index:

  $('.second').children().eq(0); 
+140
Jan 19 '12 at 13:22
source share

There is the following way to select the 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) 
+8
Dec 14 '15 at 12:34
source share

You can get the first element through an index selector:

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

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

+3
Jan 19 '12 at 13:21
source share
 $('.second').find('div:first') 
+2
Jan 19 2018-12-01T00:
source share

Doesn't nth-child return siblings, not children?

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

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

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

should give you the first class brother '.selector'

+1
Dec 10 '14 at 15:01
source share

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

Disclaimer: Browser compatibility on getElementsByClassName and firstElementChild unstable. DOM pads fix these problems.

-6
Jan 19 2018-12-12T00:
source share



All Articles