Upgrade to ExtJS 4.0.1 - Released 05/18/2011
[extjs.git] / src / core / src / dom / DomQuery.js
1 /*
2  * This is code is also distributed under MIT license for use
3  * with jQuery and prototype JavaScript libraries.
4  */
5 /**
6  * @class Ext.DomQuery
7 Provides high performance selector/xpath processing by compiling queries into reusable functions. New pseudo classes and matchers can be plugged. It works on HTML and XML documents (if a content node is passed in).
8 <p>
9 DomQuery supports most of the <a href="http://www.w3.org/TR/2005/WD-css3-selectors-20051215/#selectors">CSS3 selectors spec</a>, along with some custom selectors and basic XPath.</p>
10
11 <p>
12 All selectors, attribute filters and pseudos below can be combined infinitely in any order. For example "div.foo:nth-child(odd)[@foo=bar].bar:first" would be a perfectly valid selector. Node filters are processed in the order in which they appear, which allows you to optimize your queries for your document structure.
13 </p>
14 <h4>Element Selectors:</h4>
15 <ul class="list">
16     <li> <b>*</b> any element</li>
17     <li> <b>E</b> an element with the tag E</li>
18     <li> <b>E F</b> All descendent elements of E that have the tag F</li>
19     <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
20     <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
21     <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
22 </ul>
23 <h4>Attribute Selectors:</h4>
24 <p>The use of &#64; and quotes are optional. For example, div[&#64;foo='bar'] is also a valid attribute selector.</p>
25 <ul class="list">
26     <li> <b>E[foo]</b> has an attribute "foo"</li>
27     <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
28     <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
29     <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
30     <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
31     <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
32     <li> <b>E[foo!=bar]</b> attribute "foo" does not equal "bar"</li>
33 </ul>
34 <h4>Pseudo Classes:</h4>
35 <ul class="list">
36     <li> <b>E:first-child</b> E is the first child of its parent</li>
37     <li> <b>E:last-child</b> E is the last child of its parent</li>
38     <li> <b>E:nth-child(<i>n</i>)</b> E is the <i>n</i>th child of its parent (1 based as per the spec)</li>
39     <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
40     <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
41     <li> <b>E:only-child</b> E is the only child of its parent</li>
42     <li> <b>E:checked</b> E is an element that is has a checked attribute that is true (e.g. a radio or checkbox) </li>
43     <li> <b>E:first</b> the first E in the resultset</li>
44     <li> <b>E:last</b> the last E in the resultset</li>
45     <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
46     <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
47     <li> <b>E:even</b> shortcut for :nth-child(even)</li>
48     <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
49     <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
50     <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
51     <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
52     <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
53     <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
54     <li> <b>E:any(S1|S2|S2)</b> an E element which matches any of the simple selectors S1, S2 or S3//\\</li>
55 </ul>
56 <h4>CSS Value Selectors:</h4>
57 <ul class="list">
58     <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
59     <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
60     <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
61     <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
62     <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
63     <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
64 </ul>
65  * @singleton
66  */
67 Ext.ns('Ext.core');
68
69 Ext.core.DomQuery = Ext.DomQuery = function(){
70     var cache = {},
71         simpleCache = {},
72         valueCache = {},
73         nonSpace = /\S/,
74         trimRe = /^\s+|\s+$/g,
75         tplRe = /\{(\d+)\}/g,
76         modeRe = /^(\s?[\/>+~]\s?|\s|$)/,
77         tagTokenRe = /^(#)?([\w-\*]+)/,
78         nthRe = /(\d*)n\+?(\d*)/,
79         nthRe2 = /\D/,
80         // This is for IE MSXML which does not support expandos.
81     // IE runs the same speed using setAttribute, however FF slows way down
82     // and Safari completely fails so they need to continue to use expandos.
83     isIE = window.ActiveXObject ? true : false,
84     key = 30803;
85
86     // this eval is stop the compressor from
87     // renaming the variable to something shorter
88     eval("var batch = 30803;");
89
90     // Retrieve the child node from a particular
91     // parent at the specified index.
92     function child(parent, index){
93         var i = 0,
94             n = parent.firstChild;
95         while(n){
96             if(n.nodeType == 1){
97                if(++i == index){
98                    return n;
99                }
100             }
101             n = n.nextSibling;
102         }
103         return null;
104     }
105
106     // retrieve the next element node
107     function next(n){
108         while((n = n.nextSibling) && n.nodeType != 1);
109         return n;
110     }
111
112     // retrieve the previous element node
113     function prev(n){
114         while((n = n.previousSibling) && n.nodeType != 1);
115         return n;
116     }
117
118     // Mark each child node with a nodeIndex skipping and
119     // removing empty text nodes.
120     function children(parent){
121         var n = parent.firstChild,
122         nodeIndex = -1,
123         nextNode;
124         while(n){
125             nextNode = n.nextSibling;
126             // clean worthless empty nodes.
127             if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
128             parent.removeChild(n);
129             }else{
130             // add an expando nodeIndex
131             n.nodeIndex = ++nodeIndex;
132             }
133             n = nextNode;
134         }
135         return this;
136     }
137
138
139     // nodeSet - array of nodes
140     // cls - CSS Class
141     function byClassName(nodeSet, cls){
142         if(!cls){
143             return nodeSet;
144         }
145         var result = [], ri = -1;
146         for(var i = 0, ci; ci = nodeSet[i]; i++){
147             if((' '+ci.className+' ').indexOf(cls) != -1){
148                 result[++ri] = ci;
149             }
150         }
151         return result;
152     };
153
154     function attrValue(n, attr){
155         // if its an array, use the first node.
156         if(!n.tagName && typeof n.length != "undefined"){
157             n = n[0];
158         }
159         if(!n){
160             return null;
161         }
162
163         if(attr == "for"){
164             return n.htmlFor;
165         }
166         if(attr == "class" || attr == "className"){
167             return n.className;
168         }
169         return n.getAttribute(attr) || n[attr];
170
171     };
172
173
174     // ns - nodes
175     // mode - false, /, >, +, ~
176     // tagName - defaults to "*"
177     function getNodes(ns, mode, tagName){
178         var result = [], ri = -1, cs;
179         if(!ns){
180             return result;
181         }
182         tagName = tagName || "*";
183         // convert to array
184         if(typeof ns.getElementsByTagName != "undefined"){
185             ns = [ns];
186         }
187
188         // no mode specified, grab all elements by tagName
189         // at any depth
190         if(!mode){
191             for(var i = 0, ni; ni = ns[i]; i++){
192                 cs = ni.getElementsByTagName(tagName);
193                 for(var j = 0, ci; ci = cs[j]; j++){
194                     result[++ri] = ci;
195                 }
196             }
197         // Direct Child mode (/ or >)
198         // E > F or E/F all direct children elements of E that have the tag
199         } else if(mode == "/" || mode == ">"){
200             var utag = tagName.toUpperCase();
201             for(var i = 0, ni, cn; ni = ns[i]; i++){
202                 cn = ni.childNodes;
203                 for(var j = 0, cj; cj = cn[j]; j++){
204                     if(cj.nodeName == utag || cj.nodeName == tagName  || tagName == '*'){
205                         result[++ri] = cj;
206                     }
207                 }
208             }
209         // Immediately Preceding mode (+)
210         // E + F all elements with the tag F that are immediately preceded by an element with the tag E
211         }else if(mode == "+"){
212             var utag = tagName.toUpperCase();
213             for(var i = 0, n; n = ns[i]; i++){
214                 while((n = n.nextSibling) && n.nodeType != 1);
215                 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
216                     result[++ri] = n;
217                 }
218             }
219         // Sibling mode (~)
220         // E ~ F all elements with the tag F that are preceded by a sibling element with the tag E
221         }else if(mode == "~"){
222             var utag = tagName.toUpperCase();
223             for(var i = 0, n; n = ns[i]; i++){
224                 while((n = n.nextSibling)){
225                     if (n.nodeName == utag || n.nodeName == tagName || tagName == '*'){
226                         result[++ri] = n;
227                     }
228                 }
229             }
230         }
231         return result;
232     }
233
234     function concat(a, b){
235         if(b.slice){
236             return a.concat(b);
237         }
238         for(var i = 0, l = b.length; i < l; i++){
239             a[a.length] = b[i];
240         }
241         return a;
242     }
243
244     function byTag(cs, tagName){
245         if(cs.tagName || cs == document){
246             cs = [cs];
247         }
248         if(!tagName){
249             return cs;
250         }
251         var result = [], ri = -1;
252         tagName = tagName.toLowerCase();
253         for(var i = 0, ci; ci = cs[i]; i++){
254             if(ci.nodeType == 1 && ci.tagName.toLowerCase() == tagName){
255                 result[++ri] = ci;
256             }
257         }
258         return result;
259     }
260
261     function byId(cs, id){
262         if(cs.tagName || cs == document){
263             cs = [cs];
264         }
265         if(!id){
266             return cs;
267         }
268         var result = [], ri = -1;
269         for(var i = 0, ci; ci = cs[i]; i++){
270             if(ci && ci.id == id){
271                 result[++ri] = ci;
272                 return result;
273             }
274         }
275         return result;
276     }
277
278     // operators are =, !=, ^=, $=, *=, %=, |= and ~=
279     // custom can be "{"
280     function byAttribute(cs, attr, value, op, custom){
281         var result = [],
282             ri = -1,
283             useGetStyle = custom == "{",
284             fn = Ext.DomQuery.operators[op],
285             a,
286             xml,
287             hasXml;
288
289         for(var i = 0, ci; ci = cs[i]; i++){
290             // skip non-element nodes.
291             if(ci.nodeType != 1){
292                 continue;
293             }
294             // only need to do this for the first node
295             if(!hasXml){
296                 xml = Ext.DomQuery.isXml(ci);
297                 hasXml = true;
298             }
299
300             // we only need to change the property names if we're dealing with html nodes, not XML
301             if(!xml){
302                 if(useGetStyle){
303                     a = Ext.DomQuery.getStyle(ci, attr);
304                 } else if (attr == "class" || attr == "className"){
305                     a = ci.className;
306                 } else if (attr == "for"){
307                     a = ci.htmlFor;
308                 } else if (attr == "href"){
309                     // getAttribute href bug
310                     // http://www.glennjones.net/Post/809/getAttributehrefbug.htm
311                     a = ci.getAttribute("href", 2);
312                 } else{
313                     a = ci.getAttribute(attr);
314                 }
315             }else{
316                 a = ci.getAttribute(attr);
317             }
318             if((fn && fn(a, value)) || (!fn && a)){
319                 result[++ri] = ci;
320             }
321         }
322         return result;
323     }
324
325     function byPseudo(cs, name, value){
326         return Ext.DomQuery.pseudos[name](cs, value);
327     }
328
329     function nodupIEXml(cs){
330         var d = ++key,
331             r;
332         cs[0].setAttribute("_nodup", d);
333         r = [cs[0]];
334         for(var i = 1, len = cs.length; i < len; i++){
335             var c = cs[i];
336             if(!c.getAttribute("_nodup") != d){
337                 c.setAttribute("_nodup", d);
338                 r[r.length] = c;
339             }
340         }
341         for(var i = 0, len = cs.length; i < len; i++){
342             cs[i].removeAttribute("_nodup");
343         }
344         return r;
345     }
346
347     function nodup(cs){
348         if(!cs){
349             return [];
350         }
351         var len = cs.length, c, i, r = cs, cj, ri = -1;
352         if(!len || typeof cs.nodeType != "undefined" || len == 1){
353             return cs;
354         }
355         if(isIE && typeof cs[0].selectSingleNode != "undefined"){
356             return nodupIEXml(cs);
357         }
358         var d = ++key;
359         cs[0]._nodup = d;
360         for(i = 1; c = cs[i]; i++){
361             if(c._nodup != d){
362                 c._nodup = d;
363             }else{
364                 r = [];
365                 for(var j = 0; j < i; j++){
366                     r[++ri] = cs[j];
367                 }
368                 for(j = i+1; cj = cs[j]; j++){
369                     if(cj._nodup != d){
370                         cj._nodup = d;
371                         r[++ri] = cj;
372                     }
373                 }
374                 return r;
375             }
376         }
377         return r;
378     }
379
380     function quickDiffIEXml(c1, c2){
381         var d = ++key,
382             r = [];
383         for(var i = 0, len = c1.length; i < len; i++){
384             c1[i].setAttribute("_qdiff", d);
385         }
386         for(var i = 0, len = c2.length; i < len; i++){
387             if(c2[i].getAttribute("_qdiff") != d){
388                 r[r.length] = c2[i];
389             }
390         }
391         for(var i = 0, len = c1.length; i < len; i++){
392            c1[i].removeAttribute("_qdiff");
393         }
394         return r;
395     }
396
397     function quickDiff(c1, c2){
398         var len1 = c1.length,
399             d = ++key,
400             r = [];
401         if(!len1){
402             return c2;
403         }
404         if(isIE && typeof c1[0].selectSingleNode != "undefined"){
405             return quickDiffIEXml(c1, c2);
406         }
407         for(var i = 0; i < len1; i++){
408             c1[i]._qdiff = d;
409         }
410         for(var i = 0, len = c2.length; i < len; i++){
411             if(c2[i]._qdiff != d){
412                 r[r.length] = c2[i];
413             }
414         }
415         return r;
416     }
417
418     function quickId(ns, mode, root, id){
419         if(ns == root){
420            var d = root.ownerDocument || root;
421            return d.getElementById(id);
422         }
423         ns = getNodes(ns, mode, "*");
424         return byId(ns, id);
425     }
426
427     return {
428         getStyle : function(el, name){
429             return Ext.fly(el).getStyle(name);
430         },
431         /**
432          * Compiles a selector/xpath query into a reusable function. The returned function
433          * takes one parameter "root" (optional), which is the context node from where the query should start.
434          * @param {String} selector The selector/xpath query
435          * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
436          * @return {Function}
437          */
438         compile : function(path, type){
439             type = type || "select";
440
441             // setup fn preamble
442             var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"],
443                 mode,
444                 lastPath,
445                 matchers = Ext.DomQuery.matchers,
446                 matchersLn = matchers.length,
447                 modeMatch,
448                 // accept leading mode switch
449                 lmode = path.match(modeRe);
450
451             if(lmode && lmode[1]){
452                 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
453                 path = path.replace(lmode[1], "");
454             }
455
456             // strip leading slashes
457             while(path.substr(0, 1)=="/"){
458                 path = path.substr(1);
459             }
460
461             while(path && lastPath != path){
462                 lastPath = path;
463                 var tokenMatch = path.match(tagTokenRe);
464                 if(type == "select"){
465                     if(tokenMatch){
466                         // ID Selector
467                         if(tokenMatch[1] == "#"){
468                             fn[fn.length] = 'n = quickId(n, mode, root, "'+tokenMatch[2]+'");';
469                         }else{
470                             fn[fn.length] = 'n = getNodes(n, mode, "'+tokenMatch[2]+'");';
471                         }
472                         path = path.replace(tokenMatch[0], "");
473                     }else if(path.substr(0, 1) != '@'){
474                         fn[fn.length] = 'n = getNodes(n, mode, "*");';
475                     }
476                 // type of "simple"
477                 }else{
478                     if(tokenMatch){
479                         if(tokenMatch[1] == "#"){
480                             fn[fn.length] = 'n = byId(n, "'+tokenMatch[2]+'");';
481                         }else{
482                             fn[fn.length] = 'n = byTag(n, "'+tokenMatch[2]+'");';
483                         }
484                         path = path.replace(tokenMatch[0], "");
485                     }
486                 }
487                 while(!(modeMatch = path.match(modeRe))){
488                     var matched = false;
489                     for(var j = 0; j < matchersLn; j++){
490                         var t = matchers[j];
491                         var m = path.match(t.re);
492                         if(m){
493                             fn[fn.length] = t.select.replace(tplRe, function(x, i){
494                                 return m[i];
495                             });
496                             path = path.replace(m[0], "");
497                             matched = true;
498                             break;
499                         }
500                     }
501                     // prevent infinite loop on bad selector
502                     if(!matched){
503                         //<debug>
504                         Ext.Error.raise({
505                             sourceClass: 'Ext.DomQuery',
506                             sourceMethod: 'compile',
507                             msg: 'Error parsing selector. Parsing failed at "' + path + '"'
508                         });
509                         //</debug>
510                     }
511                 }
512                 if(modeMatch[1]){
513                     fn[fn.length] = 'mode="'+modeMatch[1].replace(trimRe, "")+'";';
514                     path = path.replace(modeMatch[1], "");
515                 }
516             }
517             // close fn out
518             fn[fn.length] = "return nodup(n);\n}";
519
520             // eval fn and return it
521             eval(fn.join(""));
522             return f;
523         },
524
525         /**
526          * Selects an array of DOM nodes using JavaScript-only implementation.
527          *
528          * Use {@link #select} to take advantage of browsers built-in support for CSS selectors.
529          *
530          * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
531          * @param {Node/String} root (optional) The start of the query (defaults to document).
532          * @return {Array} An Array of DOM elements which match the selector. If there are
533          * no matches, and empty Array is returned.
534          */
535         jsSelect: function(path, root, type){
536             // set root to doc if not specified.
537             root = root || document;
538
539             if(typeof root == "string"){
540                 root = document.getElementById(root);
541             }
542             var paths = path.split(","),
543                 results = [];
544
545             // loop over each selector
546             for(var i = 0, len = paths.length; i < len; i++){
547                 var subPath = paths[i].replace(trimRe, "");
548                 // compile and place in cache
549                 if(!cache[subPath]){
550                     cache[subPath] = Ext.DomQuery.compile(subPath);
551                     if(!cache[subPath]){
552                         //<debug>
553                         Ext.Error.raise({
554                             sourceClass: 'Ext.DomQuery',
555                             sourceMethod: 'jsSelect',
556                             msg: subPath + ' is not a valid selector'
557                         });
558                         //</debug>
559                     }
560                 }
561                 var result = cache[subPath](root);
562                 if(result && result != document){
563                     results = results.concat(result);
564                 }
565             }
566
567             // if there were multiple selectors, make sure dups
568             // are eliminated
569             if(paths.length > 1){
570                 return nodup(results);
571             }
572             return results;
573         },
574
575         isXml: function(el) {
576             var docEl = (el ? el.ownerDocument || el : 0).documentElement;
577             return docEl ? docEl.nodeName !== "HTML" : false;
578         },
579
580         /**
581          * Selects an array of DOM nodes by CSS/XPath selector.
582          *
583          * Uses [document.querySelectorAll][0] if browser supports that, otherwise falls back to
584          * {@link #jsSelect} to do the work.
585          * 
586          * Aliased as {@link Ext#query}.
587          * 
588          * [0]: https://developer.mozilla.org/en/DOM/document.querySelectorAll
589          *
590          * @param {String} path The selector/xpath query
591          * @param {Node} root (optional) The start of the query (defaults to document).
592          * @return {Array} An array of DOM elements (not a NodeList as returned by `querySelectorAll`).
593          * Empty array when no matches.
594          * @method
595          */
596         select : document.querySelectorAll ? function(path, root, type) {
597             root = root || document;
598             if (!Ext.DomQuery.isXml(root)) {
599             try {
600                 var cs = root.querySelectorAll(path);
601                 return Ext.Array.toArray(cs);
602             }
603             catch (ex) {}
604             }
605             return Ext.DomQuery.jsSelect.call(this, path, root, type);
606         } : function(path, root, type) {
607             return Ext.DomQuery.jsSelect.call(this, path, root, type);
608         },
609
610         /**
611          * Selects a single element.
612          * @param {String} selector The selector/xpath query
613          * @param {Node} root (optional) The start of the query (defaults to document).
614          * @return {Element} The DOM element which matched the selector.
615          */
616         selectNode : function(path, root){
617             return Ext.DomQuery.select(path, root)[0];
618         },
619
620         /**
621          * Selects the value of a node, optionally replacing null with the defaultValue.
622          * @param {String} selector The selector/xpath query
623          * @param {Node} root (optional) The start of the query (defaults to document).
624          * @param {String} defaultValue
625          * @return {String}
626          */
627         selectValue : function(path, root, defaultValue){
628             path = path.replace(trimRe, "");
629             if(!valueCache[path]){
630                 valueCache[path] = Ext.DomQuery.compile(path, "select");
631             }
632             var n = valueCache[path](root), v;
633             n = n[0] ? n[0] : n;
634
635             // overcome a limitation of maximum textnode size
636             // Rumored to potentially crash IE6 but has not been confirmed.
637             // http://reference.sitepoint.com/javascript/Node/normalize
638             // https://developer.mozilla.org/En/DOM/Node.normalize
639             if (typeof n.normalize == 'function') n.normalize();
640
641             v = (n && n.firstChild ? n.firstChild.nodeValue : null);
642             return ((v === null||v === undefined||v==='') ? defaultValue : v);
643         },
644
645         /**
646          * Selects the value of a node, parsing integers and floats. Returns the defaultValue, or 0 if none is specified.
647          * @param {String} selector The selector/xpath query
648          * @param {Node} root (optional) The start of the query (defaults to document).
649          * @param {Number} defaultValue
650          * @return {Number}
651          */
652         selectNumber : function(path, root, defaultValue){
653             var v = Ext.DomQuery.selectValue(path, root, defaultValue || 0);
654             return parseFloat(v);
655         },
656
657         /**
658          * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
659          * @param {String/HTMLElement/Array} el An element id, element or array of elements
660          * @param {String} selector The simple selector to test
661          * @return {Boolean}
662          */
663         is : function(el, ss){
664             if(typeof el == "string"){
665                 el = document.getElementById(el);
666             }
667             var isArray = Ext.isArray(el),
668                 result = Ext.DomQuery.filter(isArray ? el : [el], ss);
669             return isArray ? (result.length == el.length) : (result.length > 0);
670         },
671
672         /**
673          * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
674          * @param {Array} el An array of elements to filter
675          * @param {String} selector The simple selector to test
676          * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
677          * the selector instead of the ones that match
678          * @return {Array} An Array of DOM elements which match the selector. If there are
679          * no matches, and empty Array is returned.
680          */
681         filter : function(els, ss, nonMatches){
682             ss = ss.replace(trimRe, "");
683             if(!simpleCache[ss]){
684                 simpleCache[ss] = Ext.DomQuery.compile(ss, "simple");
685             }
686             var result = simpleCache[ss](els);
687             return nonMatches ? quickDiff(result, els) : result;
688         },
689
690         /**
691          * Collection of matching regular expressions and code snippets.
692          * Each capture group within () will be replace the {} in the select
693          * statement as specified by their index.
694          */
695         matchers : [{
696                 re: /^\.([\w-]+)/,
697                 select: 'n = byClassName(n, " {1} ");'
698             }, {
699                 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
700                 select: 'n = byPseudo(n, "{1}", "{2}");'
701             },{
702                 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
703                 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
704             }, {
705                 re: /^#([\w-]+)/,
706                 select: 'n = byId(n, "{1}");'
707             },{
708                 re: /^@([\w-]+)/,
709                 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
710             }
711         ],
712
713         /**
714          * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
715          * New operators can be added as long as the match the format <i>c</i>= where <i>c</i> is any character other than space, &gt; &lt;.
716          */
717         operators : {
718             "=" : function(a, v){
719                 return a == v;
720             },
721             "!=" : function(a, v){
722                 return a != v;
723             },
724             "^=" : function(a, v){
725                 return a && a.substr(0, v.length) == v;
726             },
727             "$=" : function(a, v){
728                 return a && a.substr(a.length-v.length) == v;
729             },
730             "*=" : function(a, v){
731                 return a && a.indexOf(v) !== -1;
732             },
733             "%=" : function(a, v){
734                 return (a % v) == 0;
735             },
736             "|=" : function(a, v){
737                 return a && (a == v || a.substr(0, v.length+1) == v+'-');
738             },
739             "~=" : function(a, v){
740                 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
741             }
742         },
743
744         /**
745 Object hash of "pseudo class" filter functions which are used when filtering selections. 
746 Each function is passed two parameters:
747
748 - **c** : Array
749     An Array of DOM elements to filter.
750     
751 - **v** : String
752     The argument (if any) supplied in the selector.
753
754 A filter function returns an Array of DOM elements which conform to the pseudo class.
755 In addition to the provided pseudo classes listed above such as `first-child` and `nth-child`,
756 developers may add additional, custom psuedo class filters to select elements according to application-specific requirements.
757
758 For example, to filter `a` elements to only return links to __external__ resources:
759
760     Ext.DomQuery.pseudos.external = function(c, v){
761         var r = [], ri = -1;
762         for(var i = 0, ci; ci = c[i]; i++){
763             // Include in result set only if it's a link to an external resource
764             if(ci.hostname != location.hostname){
765                 r[++ri] = ci;
766             }
767         }
768         return r;
769     };
770
771 Then external links could be gathered with the following statement:
772
773     var externalLinks = Ext.select("a:external");
774
775         * @markdown
776         */
777         pseudos : {
778             "first-child" : function(c){
779                 var r = [], ri = -1, n;
780                 for(var i = 0, ci; ci = n = c[i]; i++){
781                     while((n = n.previousSibling) && n.nodeType != 1);
782                     if(!n){
783                         r[++ri] = ci;
784                     }
785                 }
786                 return r;
787             },
788
789             "last-child" : function(c){
790                 var r = [], ri = -1, n;
791                 for(var i = 0, ci; ci = n = c[i]; i++){
792                     while((n = n.nextSibling) && n.nodeType != 1);
793                     if(!n){
794                         r[++ri] = ci;
795                     }
796                 }
797                 return r;
798             },
799
800             "nth-child" : function(c, a) {
801                 var r = [], ri = -1,
802                     m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a),
803                     f = (m[1] || 1) - 0, l = m[2] - 0;
804                 for(var i = 0, n; n = c[i]; i++){
805                     var pn = n.parentNode;
806                     if (batch != pn._batch) {
807                         var j = 0;
808                         for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
809                             if(cn.nodeType == 1){
810                                cn.nodeIndex = ++j;
811                             }
812                         }
813                         pn._batch = batch;
814                     }
815                     if (f == 1) {
816                         if (l == 0 || n.nodeIndex == l){
817                             r[++ri] = n;
818                         }
819                     } else if ((n.nodeIndex + l) % f == 0){
820                         r[++ri] = n;
821                     }
822                 }
823
824                 return r;
825             },
826
827             "only-child" : function(c){
828                 var r = [], ri = -1;;
829                 for(var i = 0, ci; ci = c[i]; i++){
830                     if(!prev(ci) && !next(ci)){
831                         r[++ri] = ci;
832                     }
833                 }
834                 return r;
835             },
836
837             "empty" : function(c){
838                 var r = [], ri = -1;
839                 for(var i = 0, ci; ci = c[i]; i++){
840                     var cns = ci.childNodes, j = 0, cn, empty = true;
841                     while(cn = cns[j]){
842                         ++j;
843                         if(cn.nodeType == 1 || cn.nodeType == 3){
844                             empty = false;
845                             break;
846                         }
847                     }
848                     if(empty){
849                         r[++ri] = ci;
850                     }
851                 }
852                 return r;
853             },
854
855             "contains" : function(c, v){
856                 var r = [], ri = -1;
857                 for(var i = 0, ci; ci = c[i]; i++){
858                     if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
859                         r[++ri] = ci;
860                     }
861                 }
862                 return r;
863             },
864
865             "nodeValue" : function(c, v){
866                 var r = [], ri = -1;
867                 for(var i = 0, ci; ci = c[i]; i++){
868                     if(ci.firstChild && ci.firstChild.nodeValue == v){
869                         r[++ri] = ci;
870                     }
871                 }
872                 return r;
873             },
874
875             "checked" : function(c){
876                 var r = [], ri = -1;
877                 for(var i = 0, ci; ci = c[i]; i++){
878                     if(ci.checked == true){
879                         r[++ri] = ci;
880                     }
881                 }
882                 return r;
883             },
884
885             "not" : function(c, ss){
886                 return Ext.DomQuery.filter(c, ss, true);
887             },
888
889             "any" : function(c, selectors){
890                 var ss = selectors.split('|'),
891                     r = [], ri = -1, s;
892                 for(var i = 0, ci; ci = c[i]; i++){
893                     for(var j = 0; s = ss[j]; j++){
894                         if(Ext.DomQuery.is(ci, s)){
895                             r[++ri] = ci;
896                             break;
897                         }
898                     }
899                 }
900                 return r;
901             },
902
903             "odd" : function(c){
904                 return this["nth-child"](c, "odd");
905             },
906
907             "even" : function(c){
908                 return this["nth-child"](c, "even");
909             },
910
911             "nth" : function(c, a){
912                 return c[a-1] || [];
913             },
914
915             "first" : function(c){
916                 return c[0] || [];
917             },
918
919             "last" : function(c){
920                 return c[c.length-1] || [];
921             },
922
923             "has" : function(c, ss){
924                 var s = Ext.DomQuery.select,
925                     r = [], ri = -1;
926                 for(var i = 0, ci; ci = c[i]; i++){
927                     if(s(ss, ci).length > 0){
928                         r[++ri] = ci;
929                     }
930                 }
931                 return r;
932             },
933
934             "next" : function(c, ss){
935                 var is = Ext.DomQuery.is,
936                     r = [], ri = -1;
937                 for(var i = 0, ci; ci = c[i]; i++){
938                     var n = next(ci);
939                     if(n && is(n, ss)){
940                         r[++ri] = ci;
941                     }
942                 }
943                 return r;
944             },
945
946             "prev" : function(c, ss){
947                 var is = Ext.DomQuery.is,
948                     r = [], ri = -1;
949                 for(var i = 0, ci; ci = c[i]; i++){
950                     var n = prev(ci);
951                     if(n && is(n, ss)){
952                         r[++ri] = ci;
953                     }
954                 }
955                 return r;
956             }
957         }
958     };
959 }();
960
961 /**
962  * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Ext.DomQuery#select}
963  * @param {String} path The selector/xpath query
964  * @param {Node} root (optional) The start of the query (defaults to document).
965  * @return {Array}
966  * @member Ext
967  * @method query
968  */
969 Ext.query = Ext.DomQuery.select;