Marian Petrov
Marian Petrov

Reputation: 625

How to get select the li tag before last li tag

<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

Answers (6)

Th0rndike
Th0rndike

Reputation: 3436

use .last() method or :last selector:

$('ul li:last').append("whatever");

Upvotes: 1

Vinayak Phal
Vinayak Phal

Reputation: 8919

Please try this:

$('ul li:last').prev();

Upvotes: 0

user1498339
user1498339

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

user1479055
user1479055

Reputation:

Use the :nth-last-child selector:

$("ul li:nth-last-child(2)")

Upvotes: 2

pimvdb
pimvdb

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

Chandu
Chandu

Reputation: 82893

Try this:

$("ul li:last").prev("li").append("<span> - Selected!</span>");

Upvotes: 1

Related Questions