Monday, July 14, 2008

Adding link separators to a unordered list using jQuery

I figured out how to easily add a separator to a inline displayed unordered list of links using jQuery and so I'd thought I share.

So for a list like so:

<ul class="subnavigation">
    <li><a href="http://damnralph.com">Damn Ralph</a></li>
    <li><a href="http://jquery.com">jQuery</a></li>
    <li><a href="http://brandensemble.com">BrandEnsemble</a></li>
</ul>


I wanted it to display like this:

Damn Ralph | jQuery | BrandEnsemble

Notice that the separator (|) is only between the links and not at either the beginning or end.  I should also note that when I was rendering the list it was coming from a dynamic source so I didn't have a set list to work from.

I wrote this jQuery:

$(document).ready(function(){
   $(".subnavigation li:lt(" + ($(".subnavigation li").length - 1) + ")").append(" | ");
});


So basically I used the :lt(index) selector to match against all the matches that were less then the index value.  I do that by figuring out the length of how many are selected and subtracting one.  Then finally I append my selector to all of my matches.


Update: John Resig (creator of jQuery) chimes in with an easier way to do the same thing in the comments.

$(document).ready(function(){
   $(".subnavigation li:not(:last-child)").append(" | ");
});

This works by selecting all the li's except the last child (or the last li) in the container. This will work with multiple containers on a page if there are more then one.  Thanks John for the tip.

Blog Posts by:

My Twitter Updates

View Twitter Page