Question

When having called .before on elements that are detached from the DOM, .end behaves differently than it does with attached elements:

var $div1 = $("div");
console.log($div1.after("foo").end());  // [document]
$div1.detach();
console.log($div1.after("foo").end());  // [<div></div>]

(Fiddle: http://jsfiddle.net/R2uc7/2/)

Apparently, .before causes different behaviour to .end depending on the node being attached or detached. I don't see the logic and I'm not sure what I can rely on.

Could someone enlighten me on the defined behaviour of .end combined with .before?

Was it helpful?

Solution

jQuery v1.7.2 uses pushStack to build the new DOM elements.

pushStack adds items to the jQuery object's stack (go figure!), and end pops the last one off, returning the rest of the stack (whatever remains).


jQuery v1.7.2 line #5860:
annotation mine

before: function() {
    if ( this[0] && this[0].parentNode ) {
        return this.domManip(arguments, false, function( elem ) {
            this.parentNode.insertBefore( elem, this );
        });
    } else if ( arguments.length ) {
        var set = jQuery.clean( arguments );
        set.push.apply( set, this.toArray() ); 
        return this.pushStack( set, "before", arguments ); //pushStack in use
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top