simonfoust.com - uncluttered, no-nonsense, handcrafted markup & css

Using jQuery to Help With Styling

First published on Mar 16, 2010 by Simon Foust

This is how I use jQuery to add a class to the last list item on navigation (or any) lists.

Generally you want to keep content, presentation, and behavior separate. CSS handles presentation, and JavaScript handles behavior. But sometimes you can rightly call on jQuery to help with styling.

For instance, let’s say you have a navigation list with a 1 pixel border in between each list item. You may accomplish this by adding the border on the right of the list item. But you don’t need the border on the last item, so you can simply specify a class called ‘last’ which doesn’t have the border.

If your navigation list is something you manage manually, then adding a class on the last list item is no problem. But if you’re using a content management system that generates your navigation list, you might not be able to easily add this class.

Or, you might have a client who wants to be able to re-order list items on the fly – and that’s when a list that is dynamically generated by your CMS comes in handy.

With this little jQuery snippet, you can have a dynamically generated navigation list like the one below and not have to worry about adding the class to the last item.

The Script:

Just before the </body> of your page, first reference jQuery as hosted by Google to save from having to load it from your own server:

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

Then you can write your jQuery line to single out the last list item and add a class to it. I usually put this line in a custom.js file. You could put it in line there on the page, but I’ve started custom.js files for all my projects recently just to keep things tidy. So I reference this:

<script src="JavaScript/custom.js"></script>

And then inside my custom.js I have the line:

$("ul#nav").find("li:last-child").addClass("last");

The CSS:

ul#nav li {
	float: left;
	padding: 0 10px;
	border-right: 1px #000 solid;
}

ul#nav li.last {
	padding-right: 0;
	border: 0;
}
« »