Different click action on the last item of a link list
Question
Let's say we have the following list:
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
<li><a href="#">Link 4 (different action)</a></li>
</ul>
Is it possible to assign a different click action on the last item of this list without any addition markup? I mean without having to add e.g a class="last" to the last item or something
Solution
Try this one:
$('ul li a').slice(-1).click(function () {
// Your general click handler here (All elements except last)
});
$('ul li:last-child a').click(function () {
// Your more specific click handler here
});
OTHER TIPS
If you mean a click event handler on only the last item:
$("ul > li:last-child").click(function() {
//
});
If you want the click handler to act differently on the last one:
$("li").click(function() {
if ($(this).is(":last-child")) {
// do something
} else {
// do something else
}
});
You can use the :last selector.
$(".yourUL li:last a").click(...);
This way you are adding the click event handler to the last li in the selected UL.
Just use the :last-child selector.
$('ul li:last-child').click(myFunc);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow