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 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *