views:

680

answers:

4

Hello, everyone

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

+3  A: 

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
  }
});
cletus
+1  A: 

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.

Vincent Ramdhanie
beware that this can cause problems when there are nested lists. Better use the direct child selector: `.yourUL > li:last`
Philippe Leybaert
agreed activa. :last doesn't tend to do what people expect.
cletus
A: 

Just use the :last-child selector.

$('ul li:last-child').click(myFunc);

+1  A: 

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
});
PatrikAkerstrand
that works. thanx :)
:last is a much worse choice than :last-child
cletus
No problem, easy fix. Still works though. I don't use JQuery myself, so I don't have intimate knowledge about it performance-wise.
PatrikAkerstrand