treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Trying to use jQuery to target the 3rd result from a wordpress loop.

  • So I am running a wordpress loop to return 3 results from the blog to be displayed in 3 columns. My problem is, that I need to remove a margin-right from the 3rd result by adding a class to the wrapping div. Here is where I'm at and totally stuck. Any help would be much appreciated, thanks.

    <script type="text/javascript">
    $('#blog-latest .blog:last').addClass('last');
    </script>

    <?php query_posts('post_per_page=3'); ?>

    <?php if(have_posts()) : while(have_posts()) : the_post(); ?>

    <div class="three-even blog">
    content here...
    </div><!--END three-even last-->

    <?php endwhile; ?>

    <?php endif; ?>
  • well i m not able to figure out all things from your example
    but one thing i have noticed is you haven't use document.ready
    so it will not apply it your code is like the one you have shown
    because dom will not be constructed when javascript will be applied...
  • I just recently changed it to the following with no changing effects.

    $(document).ready(function(){
    $('#blog-latest .blog:last').addClass('last');
    });
  • We can't see in your code if those .blog divs are really within another element with #blog-latest, so make sure that is true.

    Otherwise: .blog:nth-child(3n) will snag every third one if you want to do it in CSS.

    Or perhaps the best way is to do it right from the PHP. Set a variable to 1, increment it at the bottom of the loop, and then if that value mod 3 == 0 then output that class name.
  • Chris,
    Thank you so much for your help. I forgot to include the #blog-latest in the above code, but its in the markup of the site. The .blog:nth-child(3n) didn't work, but changing it to nth-child(5n) did the job, still looking into this. I am still learning everything right now so don't understand either option, however I was able to read up in nth-child, but still trying to lookup the PHP way of doing it to understand that. Thanks again.