Reputation: 16714
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
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
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