Diego
Diego

Reputation: 16714

jQuery :last selector odd behavior

The :last selector is, in some cases, returning more than one element. Here there is a jsfiddle to try it because its hard to believe!

Code one fails:

alert($(".child").find("span:last").length); // -> alerts 3

jQuery documentation:

Description: Selects the last matched element.

Note that :last selects a single element by filtering the current jQuery collection and matching the last element within it.

Am I missing something or this is a bug?

Upvotes: 0

Views: 60

Answers (3)

user1726343
user1726343

Reputation:

Dissecting your test, we have:

var matches = [];
$('.child').each(function(){
    //get collection of all spans in the element
    var collection = $('span',this);

    //NOTE: There is only 1 span in collection at this point

    //get last element
    var match = collection.last();
    matches.push(match);
});
alert(matches.length); //which is obviously 3

Upvotes: 0

BoltClock
BoltClock

Reputation: 723638

When you use .find() with :first and :last, it searches for the first and last element relatively to each ancestor element that was found using $('.child').

Since you have three .child elements, you have three elements in which to search for spans. Since each .child has exactly one span, :last turns up each one of those three in the context of .find(). Then .find() collects them all together, and so you have three span elements as a result.

Upvotes: 3

Kevin
Kevin

Reputation: 222

It's normal, I think what you need is:

alert( $(".child:last").find("span:last").length );

Because otherwise with only "child" as selection you will always enter the first.

Upvotes: 0

Related Questions