OK, this is a little behind the times since I'm talking about jQuery 1.3.2 - but it may be useful to someone.

Today I was working on a project which had some time ago been upgraded from jQuery 1.3.2 to the latest version, and shortly after, a bug was raised. This bug was caused by a change to the andSelf function.

This function takes the results of the previous two sets of matched elements and unions them together. jQuery can do this because it maintains an internal stack of matched elements. For example, take the following HTML:

	<ul>
	   <li>Andy</li>
	   <li>Bob</li>
	   <li class="c">Carol</li>
	   <li>Dave</li>
	</ul>

...and take the following piece of jQuery code. This will select the li elements, and then filter down to those containing a 'c' class. Finally, the call to andSelf performs a union between those two sets of elements.

	$('li').filter('.c').andSelf();

In jQuery 1.3.2, we have the following result:

[<li class="c">Carol</li>, <li>Andy</li>, <li>Bob</li>, <li>Dave</li>]

Notice that the result of the second jQuery function (filter) is at the start of the list. The remaining elements are appended to the end.

Now try the same code with jQuery 1.4.0 or above and we get this:

[<li>Andy</li>, <li>Bob</li>, <li class="c">Carol</li>, <li>Dave</li>]

We now notice that the elements have been sorted into document order before being returned.