Search code examples
jqueryjquery-pluginsjquery-end

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");

Solution

  • 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