Click here to Skip to main content
15,881,248 members
Articles / Programming Languages / Javascript

Undocumented Changes to jQuery “andSelf”

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
2 Jun 2011CPOL1 min read 10.9K   3  
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)


Written By
Software Developer Repstor Ltd
United Kingdom United Kingdom
I am a Product Architect at Repstor.

Repstor custodian and Repstor Provisioning Engine provide case management and provisioning for SharePoint.

Repstor affinity provides uninterrupted access to content systems, like SharePoint through the familiar interface of Microsoft Outlook.

Comments and Discussions

 
-- There are no messages in this forum --