Samuz Posted May 3, 2012 Share Posted May 3, 2012 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! Quote Link to comment Share on other sites More sharing options...
Jessica Posted May 3, 2012 Share Posted May 3, 2012 try $('.container .top).first('.sub').addclass('selected'); If that doesn't work you may need to use each(); Quote Link to comment Share on other sites More sharing options...
Samuz Posted May 3, 2012 Author Share Posted May 3, 2012 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. Quote Link to comment Share on other sites More sharing options...
Jessica Posted May 3, 2012 Share Posted May 3, 2012 $('#container .top').children('.sub:first-child').addClass('selected'); That works for me. Make sure you change container from . to # Quote Link to comment Share on other sites More sharing options...
Samuz Posted May 3, 2012 Author Share Posted May 3, 2012 $('#container .top').children('.sub:first-child').addClass('selected'); That works for me. Make sure you change container from . to # Thanks, that worked a charm! Quote Link to comment Share on other sites More sharing options...
Jessica Posted May 3, 2012 Share Posted May 3, 2012 No problem. I just made a page on my localhost with the code and played with it till it worked, some of those tree traversals are tricky. Quote Link to comment Share on other sites More sharing options...
haku Posted May 6, 2012 Share Posted May 6, 2012 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/ Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.