Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the jQuery pushStack function work?

Tags:

jquery

I'm having trouble understanding the jQuery pushStack function (documented at http://api.jquery.com/pushStack/). I have tried to add a list of items to a selector in this Fiddle.

http://jsfiddle.net/johnhoffman/hTh8D/

JS:

$(function() {
   var listStuff = $("p");
   listStuff.pushStack($("div"));
   listStuff.css("color", "#f00");        
});​

HTML:

<p>foo</p>
<div>bar</div>​

However, the text of the div element is not red. What does it mean to push an element onto a jQuery stack?

like image 578
John Hoffman Avatar asked Apr 17 '12 19:04

John Hoffman


1 Answers

.pushStack() creates a new jQuery object that inherits state from a previous jQuery object.

This inherited state allows methods like .end() and .self() to work properly. In your particular code example, you aren't using the return value from .pushStack() which is the new jQuery object.

When working with jQuery objects, it's important to know that most operations that change what DOM objects are in a jQuery object return a new jQuery object with the change in it rather than modifying the existing jQuery object. It is this design characteristic that allows them to maintain this stack of previously modified jQuery objects.

In your case, I don't think you need to use .pushStack() at all and you can probably just use .add() (which also returns a new jQuery object) but it isn't exactly clear to me what you're trying to do so I'm not sure exactly what code to recommend.

To achieve the end result HTML you showed in your question, you could do this:

$(function() {
   $("p").add("div").css("color", "#f00").appendTo(document.body);        
});​

You could obviously change the .appendTo() to whatever you intend to do with the new DOM objects.

In your comments you asked some more about when one would use pushStack(). I think the main use is in jQuery methods that return a new jQuery object. In that case, you create the new list of elements you want in the new jQuery object and then rather than just turning that into a regular jQuery object and returning it, you call return this.pushStack(elems). This ends up creating a new jQuery object and returning it, but it also links that new object to the previous object so that special commands like .end() can work when used in chaining.

The jQuery .add() method is a classic example. In pseudo-code, what it does is this:

add: function(selector, context) {
    // get the DOM elements that correspond to the new selector (the ones to be added)
    // get the DOM elements from the current jQuery object with this.get()
    // merge the two arrays of elements together into one array
    return this.pushStack(combinedElems);
}
like image 77
jfriend00 Avatar answered Sep 23 '22 11:09

jfriend00