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!

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.