Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Undocumented changes to jQuery “andSelf”

, 2 Jun 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

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

License

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

Share

About the Author

Jonathan Cardy
Software Developer Repstor Ltd
United Kingdom United Kingdom
I am a Software Developer at Repstor.

Repstor’s products enable the successful adoption of content management systems within organizations. Repstor affinity provides uninterrupted access to content systems, like SharePoint through the familiar interface of Microsoft Outlook. Repstor assist provides facilitated filing for all users by suggesting the most suitable location for new content based on best practice filing.
Follow on   Twitter

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141220.1 | Last Updated 2 Jun 2011
Article Copyright 2011 by Jonathan Cardy
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid