how to add class "last" to every div number 4 , 8 , 12 , 16 etc . i think this is not big problem right ?
Before :
<div id="main">
<div>Element 1</div>
<div>Element 2</div>
<div>Element 3</div>
<div>Element 4</div>
<div>Element 5</div>
<div>Element 6</div>
<div>Element 7</div>
<div>Element 8</div>
<div>Element 9</div>
<div>Element 10</div>
<div>Element 11</div>
<div>Element 12</div>
</div>
After
<div id="main">
<div>Element 1</div>
<div>Element 2</div>
<div>Element 3</div>
<div class="last">Element 4</div>
<div>Element 5</div>
<div>Element 6</div>
<div>Element 7</div>
<div class="last">Element 8</div>
<div>Element 9</div>
<div>Element 10</div>
<div>Element 11</div>
<div class="last">Element 12</div>
</div>
Thanks.
how to add class "last" to every div number 4 , 8 , 12 , 16 etc . i think this is not big problem right ?
Before :
<div id="main">
<div>Element 1</div>
<div>Element 2</div>
<div>Element 3</div>
<div>Element 4</div>
<div>Element 5</div>
<div>Element 6</div>
<div>Element 7</div>
<div>Element 8</div>
<div>Element 9</div>
<div>Element 10</div>
<div>Element 11</div>
<div>Element 12</div>
</div>
After
<div id="main">
<div>Element 1</div>
<div>Element 2</div>
<div>Element 3</div>
<div class="last">Element 4</div>
<div>Element 5</div>
<div>Element 6</div>
<div>Element 7</div>
<div class="last">Element 8</div>
<div>Element 9</div>
<div>Element 10</div>
<div>Element 11</div>
<div class="last">Element 12</div>
</div>
Thanks.
Share Improve this question asked May 21, 2012 at 7:36 ruslyrossiruslyrossi 3661 gold badge6 silver badges21 bronze badges3 Answers
Reset to default 11$('#main > div:nth-child(4n)').addClass('last');
example fiddle: http://jsfiddle/T7fE6/
Note: if you have to apply some style to those elements (and you're not supporting IE8 or previous IE browsers) you could simply define that selector into your CSS, e.g.
#main > div:nth-child(4n) {
/* supported by IE9+ and all modern browser */
}
If your markup really will be only div
elements, then F. Calderan's answer is the way to go.
If you may also have other elements in there and you want to ignore those, you'd do this:
$("#main > div").filter(function(index) {
return index % 4 === 3;
}).addClass("last");
Live example | source
That's because even though div:nth-child(4n)
looks like it means every four divs, it doesn't; it means divs that are the 4th, 8th, etc. element in their parent container. So if you throw others in there, it won't work.
But again, if you only have div
s, F's answer is the way to go.
you can do this
$(document).ready(function(){
$('#main div').each(function(e){
if((e+1) % 4 == 0){
$(this).addClass('last');
}
});
})
here is the running example
Find the example here
hope it helped...