Jump to content

jQuery select every first element in a div


Samuz

Recommended Posts

I have some html like this:

 

<div id="container">

<div class="top">

<div class="sub" id="one1">
some text
</div>
<div class="sub" id="two1">
some text
</div>
<div class="sub" id="three1">
some text
</div>
</div>

<div class="top">

<div class="sub" id="one2">
some text
</div>
<div class="sub" id="two2">
some text
</div>
<div class="sub" id="three2">
some text
</div>
</div>

<div class="top">

<div class="sub" id="one3">
some text
</div>
<div class="sub" id="two3">
some text
</div>
<div class="sub" id="three3">
some text
</div>
</div>

</div>

 

I tried this:

 

$('.container .top .sub:first-child').addClass('selected');

 

That didn't work.

 

Also tried

 

$('.container .top .sub).first().addclass('selected');

But this only affected the first .sub that appeared.

 

 

How do I select all the first .sub div's that are within the parent class 'top'.

 

Looking forward to answers!

try

$('.container .top).first('.sub').addclass('selected');

If that doesn't work you may need to use each();

Thanks for the reply, didn't work however. :( It applied '.selected' to .top :S

 

Anyway, i'm looking into each() now. If you have any ideas that could help me, that'd be great too.

How do I select all the first .sub div's that are within the parent class 'top'.

 

You should also be able to use this:

 

$(".top .sub:nth-child(1)")

 

:nth-child gives you all the elements that are that child of their parent. In this case the first child of their parent.

 

http://api.jquery.com/nth-child-selector/

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.