Loading...
10th Jan 2010#

Adding a css class to last div using jQuery

This is an issue I come across from time to time, especially when using wordpress or anything else that dynamically produces content.

The scenario is you have a list of posts on a page and you’re not able to add a class to the last item in the list (say to remove a separating border).

One option would be to to use the pseudo css class :last-child in your css e.g:

1
.post:last-child{border-bottom:none;}

This would then remove the border on the last post div, which is a nice simple fix. The only downside is that :last-child doesn’t work in IE7+8 (surprise surprise).

So here is a nice simple jQuery fix to the problem.

First off we’ll call the jQuery:

You can choose to download the file from the jQuery site, or you can use this one hosted on Google.

1
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

Then include this piece of javascript in your head section:

1
2
3
4
5
<script type="text/javascript">
jQuery(document).ready(function () {
	jQuery('.post:last').addClass('last');
});
</script>

This tells the div class ‘post’ to add class ‘last’. All you have to do is replace ‘post’ with the name of the css class you want ‘last’ adding to.

Hey presto your last item will now look like this:

1
<div class="post last">

This will now allow you to add this in your css file

1
.post.last{border-bottom:none;}

Thus removing the border off the very last div :-)

Written by Alex Murphy

Hey! My name is Alex and I'm a UK based web designer specialising in wordpress, front-end design and head designer here at GoMySites.

5 Comments

  1. Great article Alex :)

  2. What is the worpress plug-in u used here for code formatting ?

  3. thanks for this script, but how ist the way if i have two columns and have to do ist in both colums separately ?
    how to change the last div.post in #col1 and #col2 ?

    • If i follow you correctly you want .last adding in 2 places (#col1 & #col2) to do that set the code like this:

      jQuery(‘#col1 .post:last, #col2 .post:last’).addClass(‘last’);

Leave a Comment