Reputation: 625
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<script>$("ul li:nth-child(3)").append("<span> - Selected!</span>");</script>
</body>
</html>
I want to select li number 3 and with :nth-child(3)
but the problem is that the li tag are random sometime it can be 6 or 9 or 20 .. so how to get the last and maybe then use prev() ?
Upvotes: 0
Views: 2879
Reputation: 3436
use .last()
method or :last
selector:
$('ul li:last').append("whatever");
Upvotes: 1
Reputation: 629
Not the most elegant way, but some time it is useful the have the list of selected elements:
var liList = $('#testUl li');
var value = $(liList[liList.length-2]).text();
Example here: http://jsfiddle.net/sx6sQ/
Upvotes: 0
Reputation: 154818
.eq
accepts negative indices, which count from the end. Note that .eq
counts on the set, not the actual child index. In your case however, the set only consists of the children of the one ul
, so that doesn't make a difference.
$("ul li").eq(-2); // -1 is last, -2 is one before last
Upvotes: 7
Reputation: 82893
Try this:
$("ul li:last").prev("li").append("<span> - Selected!</span>");
Upvotes: 1