Lancelot
Lancelot

Reputation: 1441

jQuery last-child Undefined Issue

I have an issue getting the ID of my last-child with jQuery.

Here is my code with issue: http://jsfiddle.net/2ePeP/

My HTML code

<div>
    <p class="category" id="category_1">Appetizer</p>
    <p class="category" id="category_2">Beaverages</p>
    <p class="category" id="category_3">Dessert</p>
    <button type="button" class="add-category">Add</button>
</div>

My JavaScript code

$('.add-category').click(function() {
    alert($('.category:last-child').attr('id'));
});

Any help will be greatly appreciated!!!

Upvotes: 3

Views: 1342

Answers (2)

andyb
andyb

Reputation: 43823

.last-child will only try to match the very last child of a parent element - see MDN :last-child, but the <button> is the last child in the parent <div>. There is no element with class="category" that is also a last child.

CSS does provide a selector that will work, which matches

the last occurrence of a specified element, even if it doesn't come dead last in the HTML.

(from CSS Tricks :last-child)

So the following will log the id of the last class="category" element.

$('.add-category').click(function() {
    console.log($('.category:last-of-type')[0].id);
});

Upvotes: 0

Anton
Anton

Reputation: 32581

Use :last or .last()

$('.category:last');

or

$('.category').last()

DEMO

Upvotes: 4

Related Questions