Apply a class to the last element in a list with jQuery
In this quick tip I’ll show you how to easily add a class to the last element in a list so that you can apply different styles to it, using a very simple, but very powerful jQuery selector.
See those lists in the sidebar over to the right of this page? Notice how the bottom item in each list doesn’t have a line beneath it? This was done by adding a class named “last” to the last <li> element in each <ul>. I did this with a really neat snippet of jQuery.
$("ul").each(function (index, domEle){
$("li:last-child").addClass("last");
});
I’ll explain what this does exactly.
$("ul").each(function (index, domEle){
This picks out each <ul> element in the page.
$("li:last-child").addClass("last");
And here we pick out the last <li> element within each <ul>. We do this by using the powerful jQuery “:last-child” selector. If we were to simply use the “:last” selector, we would only be selecting the final <li> element in the page, rather than in each <ul> element. Once we have everything selected, we simply use “addClass” to apply our class.
Finally, removing the border is as simple as editing the CSS for the “.last” class.
.last { border-bottom: none; }
Hope this helps!








No Comments Yet
You can be the first to comment!
Leave a comment