Kim
Kim

Reputation: 1148

Select child elements from child X to child X

I need to add a class to child x to child x inside a div.

So in this example I want to add the class to child 3,4,5,6,7,8,9,10.

Now it's just adding the class to every third element.

Any good suggestions how this could be accomplished?

I have this HTML:

  <div id="days">
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
  </div>

Jquery:

 day = 3;
 child_count = 10;
 $('#days > div:nth-child(' + day + 'n+' + child_count + ')').addClass('done');

Upvotes: 0

Views: 61

Answers (3)

gdoron
gdoron

Reputation: 150313

Your best option is actually very simple:

$('#days > div').slice(start, end).addClass('done');

(start and end are zero based indexes)

DEMO
Docs

Upvotes: 3

PSL
PSL

Reputation: 123749

Another way, using :gt and :lt:

$("#days > div:gt(" + (day-2) + ")").filter(':lt(' + (child_count) + ')').addClass('done');

Fiddle

All indexes for lt and gt are 0 based. gt will select the items greater than your start count, so gt will be day-2 i.e select all greater than index 1, (i.e 2nd which is 3rd item), and filter it to get the items less than your count.

Upvotes: 1

Tats_innit
Tats_innit

Reputation: 34117

OR could do this : http://jsfiddle.net/ZpZhk/ OR this http://jsfiddle.net/NzGVW/

Please note this is not dynamic and only cater ur specific case.

API .netUntil http://api.jquery.com/nextUntil/

API: .nextAll http://api.jquery.com/nextAll/

Hope it fits your specific needs else above is good :)

code

 $('#days > div:nth-child(3)').nextAll().addClass('done');

 alert($('#days').html());

Update

 $('#days > div:nth-child(3)').nextUntil($('#days > div:nth-child(10)') , "div" ).addClass('done');

Upvotes: 1

Related Questions