Add margin to every 2nd, 5th, 8th, 11th etc. class element

css-selectors, javascript, jquery, margin

Solution

Try use nth-child selector from jQuery

$('div:nth-child(3n - 1)').css('margin-top', '10px')

Demo: Fiddle

Problem

I have a webpage filling with a variabel number of the same class elements. I want to set a left and right margin to every 2nd, 5th, 8th, 11th etc. class (if present). Is there a way to achieve this with javascript? I don't want to use css3 child selectors, because of it's non-compatibility on older browsers. My divs are placed like this: [div class="block"][div class="block"][div class="block"] [div class="block"][div class="block"][div class="block"] [div class="block"][div class="block"][div class="block"] [div class="block"][div class="block"][div class="block"] I want every middle div to have a margin left and right. Thank you. :)

Original source