Got some code here that isn't working:
$("#sidebar ul li:last").each(function(){
$(this).addClass("last");
});
Basically I have 3 lists and want to add a class (last) to each item appearing last in each unordered list.
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li class="last">Item 3</li>
</ul>
Hope that makes sense, Cheers!
Easy mistake to make. Try this:
$("#sidebar ul li:last-child").addClass("last");
Basically :last doesn't quite do what you think it does. It only matches the very last in the document, not the last in each list. That's what :last-child is for.
with jquery add this
$("ul li").last().addClass('last');
The reason that won't work is due to the fact that :last
only matches one element. From the jQuery documentation:
Matches the last selected element.
So what your code is doing is getting a set of all the <li>
elements in a <ul>
and then from that set taking the last value. Example:
<ul>
<li>1</li>
<li>2</li>
</ul>
<ul>
<li>3</li>
<li>4</li>
</ul>
<ul>
<li>5</li>
<li>6</li>
</ul>
Your code would return the element <li>6</li>
. (Internally, it'd collect <li>1</li>
to <li>6</li>
and then lop off the last one and return it).
What you're looking for is what the other answers here have said: :last-child
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With