views:

242

answers:

2

Hi Guys,

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');
+4  A: 

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');
Nick Craver
Bootfull!, thanks a million Nick, you are a star!!!
Keith Donegan
Yes totally agree on that :D +1
c0mrade
I am confused (after looking at his page), should this not be the nth instance within tags with that class? Why would the sibling h1 matter? should he use :eq(n) instead?
Mark Schultheiss
I guess I need to research the nth child stuff some :) (duh, nth child of parent, not nth instance of the selected elements :) I should have read more first :)
Mark Schultheiss
@Mark - That's the confusing part I mentioned :) the `n` doesn't care about the class selector, `:nth-child` is it's *own* selector, just like `:last` or `:not()`, etc...so it's matching the fact that it's `class="photo_post_thumbnail"` **and** `:nth-child(3n+1)`, the `n` doesn't care about the class that's a different selector. Before your div was the 3rd child **and** had that class, so it matched. What you want is to match that class and every 3rd child + 1 offset for the `<h1>`, that make more sense?
Nick Craver
+3  A: 

Alternative solution :

   $('.photo_post_thumbnail').each(function(i) {
      i=(i+1);
      if(i%3==0){
     $(this).css("margin-right","0px"));
    }
   });
c0mrade
I think you meant `$('.photo_post_thumbnail').each(function(i) {` here, the `$.each()` expects a collection as the first argument :)
Nick Craver
@Nick Craver I did, thank you for the fix
c0mrade
+1 for a correct alternative :)
Nick Craver