- From: John Resig <jresig@mozilla.com>
- Date: Thu, 24 Sep 2009 09:34:40 -0400
- To: Lachlan Hunt <lachlan.hunt@lachy.id.au>
- Cc: Sean Hogan <shogun70@westnet.com.au>, public-webapps <public-webapps@w3.org>, Garrett Smith <dhtmlkitchen@gmail.com>, Jonas Sicking <jonas@sicking.cc>
- Message-ID: <730bab940909240634p3e6d9bc3v92239fdb3271104f@mail.gmail.com>
> Filtering NodeLists/StaticNodeLists, Queries on NodeLists/StaticNodeLists:
>> Neither of these are useful, as is, to libraries. What is actually useful
>> is
>> the ability to run these against an array (or array-like collection) of
>> DOM
>> nodes.
>>
>
> I believe this would be handled using the Array.filter() method, with a
> callback that checks if the selector matches the element, as Jonas pointed
> out:
>
> filteredArray = myArrayOfNodes.filter(function(node) { return
>> node.matchesSelector("some>selector"); });
>>
>
> (That could also work with the above Selector.matches() proposal)
>
Array.filter() will meet the need of filtering
NodeLists/StaticNodeLists/Arrays of Elements - sure - but it won't meet the
need of NodeList.querySelectorAll (especially if that works with an
array-like collection of DOM elements).
The problem is that when you have multiple collections of DOM elements and
you wish to reduce them to a single collection it ends up being a very
expensive task. The steps are as follows:
- The collections must be merged together into a single array of DOM
elements.
- The elements must be sorted to be in document order.
- Duplicate elements must be removed from the collection.
The relevant pieces of code from the Sizzle selector engine can be found
here:
http://github.com/jeresig/sizzle/blob/master/sizzle.js#L134
http://github.com/jeresig/sizzle/blob/master/sizzle.js#L702
As you can probably tell - those sorting functions are very, very,
time-consuming - but are 100% necessary if we wish to return results in the
correct order.
It would be great to have a separate, standalone, function that handles
these merge/sort/unique operations for collections of DOM elements
(especially if they're disconnected from the document!).
For example in jQuery you can do:
$(".foo").parents()
(this returns all ancestors of all elements that have a class of "foo")
Those results must be merged/sorted/uniqued in order to be correctly
returned to the user - and since .parents() (or similar) is not
functionality in CSS 3 we're forced to roll our own.
If there was a merge/sort/unique method it would drop the need for having a
NodeList/Array.querySelectorAll.
--John
Received on Thursday, 24 September 2009 13:35:34 UTC