Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add class "last" to every div number 4 , 8 , 12 , 16 etc

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.

like image 877
ruslyrossi Avatar asked Dec 06 '22 14:12

ruslyrossi


1 Answers

$('#main > div:nth-child(4n)').addClass('last');

example fiddle: http://jsfiddle.net/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 */
 }
like image 180
Fabrizio Calderan Avatar answered Jan 01 '23 03:01

Fabrizio Calderan