Kevin
Kevin

Reputation: 25269

jquery before() function

I have a form something like this:

<form>
    <ul>
        <li>...</li>
        <li><input type="submit" value="go" /></li>
    </ul>
</form>

And then a jquery expression like this:

$(document).ready(function() {
    $('#addField').click(function() {
        var cloned = $('#someid').clone(true);
        $('ul:last-child').before(cloned); // <-- this doesn't work
    });
});

And jquery inserts the cloned object before the UL, not before the last child of the UL, as intended. If I change the jquery expression to "form ul:last-child" then it inserts before the form. What am I doing wrong?

Upvotes: 0

Views: 129

Answers (2)

Andri
Andri

Reputation: 1503

specifying ul:last-child select the ul that is the last child of its parent. what you are looking for is ul :last-child. This will select the last child of the ul.

Upvotes: 0

SLaks
SLaks

Reputation: 887657

ul:last-child matches a <ul> which is the last child of its parent.

You want ul li:last-child, which matches an <li> which is the last child of its parent and which is in a <ul>.

Upvotes: 3

Related Questions