Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery nth-child not working properly

I am using JQuery's nth-child selector to alter the margin on every 3rd div with a class of photo_post_thumbnail, but it alters it every 2nd div?

Can anyone spot what I am doing wrong?

Site

http://www.clients.eirestudio.net/hatstand/wordpress/photos/

HTML markup

<div class="postbox photo_post_thumbnail">
      blah blah
</div>

<div class="postbox photo_post_thumbnail">
      blah blah
</div>

<div class="postbox photo_post_thumbnail">
      blah blah
</div>

JQuery Code

$('.photo_post_thumbnail:nth-child(3n)').css('margin-right', '0px');
like image 693
Keith Donegan Avatar asked Apr 23 '10 13:04

Keith Donegan


2 Answers

It's doing this because you have a <h1> before those divs, making that div the 4th child not the third :)

The nth-child selector is a bit confusing at first because it's the nth-child of the parent, not just the nth-child matching that selector of the parent, the selector has no bearing the position for this selector.

To get the div you want, do 3n+1 like this:

$('.photo_post_thumbnail:nth-child(3n+1)').css('margin-right', '0px');
like image 89
Nick Craver Avatar answered Sep 18 '22 03:09

Nick Craver


Alternative solution :

   $('.photo_post_thumbnail').each(function(i) {
      i=(i+1);
      if(i%3==0){
     $(this).css("margin-right","0px"));
    }
   });
like image 29
ant Avatar answered Sep 21 '22 03:09

ant