Add a class "last" to each div 4, 8, 12, 16, etc.

how to add the class "last" to each div 4, 8, 12, 16, etc. I think this is not a big problem?

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.

+4
source share
3 answers

If your markup is really only a div , then F. Calder's answer is the way to go.

If you can have other elements and want to ignore them, you should do this:

 $("#main > div").filter(function(index) { return index % 4 === 3; }).addClass("last"); 

Live example | a source

This is because although div:nth-child(4n) looks like it means every four divs, it is not; this means divs that are 4th, 8th, etc. an element in the parent container. Therefore, if you throw others there, it will not work.

But then again, if you only have div s, the F answer is the way to go.

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

Sample script: http://jsfiddle.net/T7fE6/

Note. If you need to apply some style to these elements (and you do not support IE8 or previous IE browsers), you can simply define this selector in your CSS, for example.

  #main > div:nth-child(4n) { /* supported by IE9+ and all modern browser */ } 
+11
source

You can do it

 $(document).ready(function(){ $('#main div').each(function(e){ if((e+1) % 4 == 0){ $(this).addClass('last'); } }); })​ 

here is an example of execution

Find an example here

hope this helped ...

+2
source

Source: https://habr.com/ru/post/1413484/


All Articles