Diego
Diego

Reputation: 16714

jQuery .end method not working with jQuery object

I have a custom plugin very simple. If it returns this after calling it, .end() works great. However if it returns $(this), .end() doesn't work. Why does that happen? Am I missing something here?

Code:

$.fn.fnBar = function() {
    $(this).html("hello!");
    //return $(this); // Doesn't work
    return this; // Works!
};


$("div")
    .find("span")
        .fnBar()
    .end()
    .css("color", "red");

Upvotes: 2

Views: 342

Answers (2)

Felix Kling
Felix Kling

Reputation: 816552

Inside a jQuery method, this is already the jQuery object. $(this) creates a completely new jQuery object, with no filtering history.

Same problem, but maybe easier to understand:

var bar = $("div").find("span");
// This doesn't work
$(bar).end().css("color", "red");
// This does
bar.end().css("color", "red");

Upvotes: 4

Denys Séguret
Denys Séguret

Reputation: 382170

From the documentation :

End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.

In

$("div").find("span").fnBar().end()

end sets the state of the filtering to the one before the call to find.

With just $(this), you're rebuilding a new jQuery object, without any history. You have no filtering operation and no chain, so it has nothing to cancel.

jQuery end function is implemented like this :

end: function() {
    return this.prevObject || this.constructor(null);
},

This means you can see the difference by logging the prevObject property of your jQuery object :

console.log(this.prevObject);
console.log($(this).prevObject); // will give undefined

Upvotes: 5

Related Questions