How to select first child with jQuery?

sameold picture sameold · May 2, 2011 · Viewed 118.9k times · Source

How do I select the first div in these divs (the one with id=div1) using first child selectors?

<div class="alldivs">
   <div class="onediv" id="div1">
   </div>
   <div class="onediv" id="div2">
   </div>
   <div class="onediv" id="div3">
   </div>
</div>

Answer

Roko C. Buljan picture Roko C. Buljan · May 2, 2011

Try with: $('.onediv').eq(0)

demo jsBin

From the demo: Other examples of selectors and methods targeting the first LI unside an UL:

.eq() Method: $('li').eq(0)
:eq() selector: $('li:eq(0)')
.first() Method $('li').first()
:first selector: $('li:first')
:first-child selector: $('li:first-child')
:lt() selector:$('li:lt(1)')
:nth-child() selector:$('li:nth-child(1)')

jQ + JS:

Array.slice() Method: $('li').slice(0,1)

you can also use [i] to get the JS HTMLelement index out of the jQuery el. (array) collection like eg:

$('li')[0]

now that you have the JS element representation you have to use JS native methods eg:

$('li')[0].className = 'active'; // Adds class "active" to the first LI in the DOM

or you can (don't - it's bad design) wrap it back into a jQuery object

$( $('li')[0] ).addClass('active'); // Don't. Use .eq() instead