Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Undocumented Changes to jQuery “andSelf”

4.00/5 (1 vote)
2 Jun 2011CPOL1 min read 11K  
How to fix a bug caused by a change to the andSelf function

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:

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.

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

In jQuery 1.3.2, we have the following result:

HTML
[<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:

XML
[<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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)