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>
Try with: $('.onediv').eq(0)
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:
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