Jasper
Jasper

Reputation: 5238

Get last li on a line jQuery

We have a simple ul

<ul>
   <li>some text</li>
   <li>some some text</li>
   <li>text more</li>
   <li>text here</li>
</ul>

ul { text-align: center; width: 100px; }
li { width: auto; display: inline; }

So the ul can have several lines. How do I take last li of the each line inside ul?

Upvotes: 4

Views: 7253

Answers (7)

Joseph Silber
Joseph Silber

Reputation: 219920

If by last li on the each line of the ul you mean the last li in each ul, then:

$('ul li:last-child');

However, if you mean that you have your li's within the same ul written up on several lines in your source code, and you now want to get the last one on each line, then the answer is that you can't. The DOM does not care about your newline characters in your code.


Note: the correct way to do this would be to give those li's a separate class.

<ul>
    <li></li><li></li><li class="last"></li>
    <li></li><li></li><li class="last"></li>
    <li></li><li></li><li class="last"></li>
</ul>

Now you can use CSS

li.last { color: #444 }

and jQuery

$('li.last');

the proper way...

Upvotes: 9

hunter
hunter

Reputation: 63512

Use the :last selector - http://api.jquery.com/last-selector/

$("ul li:last");

and if you're trying to find the last li for multiple ul's try this:

var $lasts = $("ul").map(function(){
    return $(this).find("li:last");
});

working example:

http://jsfiddle.net/hunter/SBsqS/

Upvotes: 1

Jamie Dixon
Jamie Dixon

Reputation: 53991

To get the last item in the list using jQuery you can simply use the last() method.

See here for more information : http://api.jquery.com/last/

var item = $('#myList li').last()

Upvotes: 1

adritha84
adritha84

Reputation: 1017

Try using :last selector: http://api.jquery.com/last-selector

Upvotes: 0

jwchang
jwchang

Reputation: 10864

This returns group of "last li on the each line of the ul"

$("ul li:last");

Upvotes: 1

DaveRandom
DaveRandom

Reputation: 88647

var theList = document.getElementById('id_of_my_ul');
var theLastItem = theList.childNodes[theList.childNodes.length - 1];

Don't know how you would do it in JQuery, but it can't be that dissimilar

Upvotes: 0

Eonasdan
Eonasdan

Reputation: 7765

see jquery .last()

$('ul li').last().css('background-color', 'red');

Upvotes: 1

Related Questions