Upgrade to ExtJS 4.0.0 - Released 04/26/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 a group of elements.
527          * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
528          * @param {Node/String} root (optional) The start of the query (defaults to document).
529          * @return {Array} An Array of DOM elements which match the selector. If there are
530          * no matches, and empty Array is returned.
531          */
532         jsSelect: function(path, root, type){
533             // set root to doc if not specified.
534             root = root || document;
535
536             if(typeof root == "string"){
537                 root = document.getElementById(root);
538             }
539             var paths = path.split(","),
540                 results = [];
541
542             // loop over each selector
543             for(var i = 0, len = paths.length; i < len; i++){
544                 var subPath = paths[i].replace(trimRe, "");
545                 // compile and place in cache
546                 if(!cache[subPath]){
547                     cache[subPath] = Ext.DomQuery.compile(subPath);
548                     if(!cache[subPath]){
549                         //<debug>
550                         Ext.Error.raise({
551                             sourceClass: 'Ext.DomQuery',
552                             sourceMethod: 'jsSelect',
553                             msg: subPath + ' is not a valid selector'
554                         });
555                         //</debug>
556                     }
557                 }
558                 var result = cache[subPath](root);
559                 if(result && result != document){
560                     results = results.concat(result);
561                 }
562             }
563
564             // if there were multiple selectors, make sure dups
565             // are eliminated
566             if(paths.length > 1){
567                 return nodup(results);
568             }
569             return results;
570         },
571
572         isXml: function(el) {
573             var docEl = (el ? el.ownerDocument || el : 0).documentElement;
574             return docEl ? docEl.nodeName !== "HTML" : false;
575         },
576         
577         select : document.querySelectorAll ? function(path, root, type) {
578             root = root || document;
579             if (!Ext.DomQuery.isXml(root)) {
580             try {
581                 var cs = root.querySelectorAll(path);
582                 return Ext.Array.toArray(cs);
583             }
584             catch (ex) {}
585             }
586             return Ext.DomQuery.jsSelect.call(this, path, root, type);
587         } : function(path, root, type) {
588             return Ext.DomQuery.jsSelect.call(this, path, root, type);
589         },
590
591         /**
592          * Selects a single element.
593          * @param {String} selector The selector/xpath query
594          * @param {Node} root (optional) The start of the query (defaults to document).
595          * @return {Element} The DOM element which matched the selector.
596          */
597         selectNode : function(path, root){
598             return Ext.DomQuery.select(path, root)[0];
599         },
600
601         /**
602          * Selects the value of a node, optionally replacing null with the defaultValue.
603          * @param {String} selector The selector/xpath query
604          * @param {Node} root (optional) The start of the query (defaults to document).
605          * @param {String} defaultValue
606          * @return {String}
607          */
608         selectValue : function(path, root, defaultValue){
609             path = path.replace(trimRe, "");
610             if(!valueCache[path]){
611                 valueCache[path] = Ext.DomQuery.compile(path, "select");
612             }
613             var n = valueCache[path](root), v;
614             n = n[0] ? n[0] : n;
615
616             // overcome a limitation of maximum textnode size
617             // Rumored to potentially crash IE6 but has not been confirmed.
618             // http://reference.sitepoint.com/javascript/Node/normalize
619             // https://developer.mozilla.org/En/DOM/Node.normalize
620             if (typeof n.normalize == 'function') n.normalize();
621
622             v = (n && n.firstChild ? n.firstChild.nodeValue : null);
623             return ((v === null||v === undefined||v==='') ? defaultValue : v);
624         },
625
626         /**
627          * Selects the value of a node, parsing integers and floats. Returns the defaultValue, or 0 if none is specified.
628          * @param {String} selector The selector/xpath query
629          * @param {Node} root (optional) The start of the query (defaults to document).
630          * @param {Number} defaultValue
631          * @return {Number}
632          */
633         selectNumber : function(path, root, defaultValue){
634             var v = Ext.DomQuery.selectValue(path, root, defaultValue || 0);
635             return parseFloat(v);
636         },
637
638         /**
639          * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
640          * @param {String/HTMLElement/Array} el An element id, element or array of elements
641          * @param {String} selector The simple selector to test
642          * @return {Boolean}
643          */
644         is : function(el, ss){
645             if(typeof el == "string"){
646                 el = document.getElementById(el);
647             }
648             var isArray = Ext.isArray(el),
649                 result = Ext.DomQuery.filter(isArray ? el : [el], ss);
650             return isArray ? (result.length == el.length) : (result.length > 0);
651         },
652
653         /**
654          * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
655          * @param {Array} el An array of elements to filter
656          * @param {String} selector The simple selector to test
657          * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
658          * the selector instead of the ones that match
659          * @return {Array} An Array of DOM elements which match the selector. If there are
660          * no matches, and empty Array is returned.
661          */
662         filter : function(els, ss, nonMatches){
663             ss = ss.replace(trimRe, "");
664             if(!simpleCache[ss]){
665                 simpleCache[ss] = Ext.DomQuery.compile(ss, "simple");
666             }
667             var result = simpleCache[ss](els);
668             return nonMatches ? quickDiff(result, els) : result;
669         },
670
671         /**
672          * Collection of matching regular expressions and code snippets.
673          * Each capture group within () will be replace the {} in the select
674          * statement as specified by their index.
675          */
676         matchers : [{
677                 re: /^\.([\w-]+)/,
678                 select: 'n = byClassName(n, " {1} ");'
679             }, {
680                 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
681                 select: 'n = byPseudo(n, "{1}", "{2}");'
682             },{
683                 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
684                 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
685             }, {
686                 re: /^#([\w-]+)/,
687                 select: 'n = byId(n, "{1}");'
688             },{
689                 re: /^@([\w-]+)/,
690                 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
691             }
692         ],
693
694         /**
695          * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
696          * 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;.
697          */
698         operators : {
699             "=" : function(a, v){
700                 return a == v;
701             },
702             "!=" : function(a, v){
703                 return a != v;
704             },
705             "^=" : function(a, v){
706                 return a && a.substr(0, v.length) == v;
707             },
708             "$=" : function(a, v){
709                 return a && a.substr(a.length-v.length) == v;
710             },
711             "*=" : function(a, v){
712                 return a && a.indexOf(v) !== -1;
713             },
714             "%=" : function(a, v){
715                 return (a % v) == 0;
716             },
717             "|=" : function(a, v){
718                 return a && (a == v || a.substr(0, v.length+1) == v+'-');
719             },
720             "~=" : function(a, v){
721                 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
722             }
723         },
724
725         /**
726 Object hash of "pseudo class" filter functions which are used when filtering selections. 
727 Each function is passed two parameters:
728
729 - **c** : Array
730     An Array of DOM elements to filter.
731     
732 - **v** : String
733     The argument (if any) supplied in the selector.
734
735 A filter function returns an Array of DOM elements which conform to the pseudo class.
736 In addition to the provided pseudo classes listed above such as `first-child` and `nth-child`,
737 developers may add additional, custom psuedo class filters to select elements according to application-specific requirements.
738
739 For example, to filter `a` elements to only return links to __external__ resources:
740
741     Ext.DomQuery.pseudos.external = function(c, v){
742         var r = [], ri = -1;
743         for(var i = 0, ci; ci = c[i]; i++){
744             // Include in result set only if it's a link to an external resource
745             if(ci.hostname != location.hostname){
746                 r[++ri] = ci;
747             }
748         }
749         return r;
750     };
751
752 Then external links could be gathered with the following statement:
753
754     var externalLinks = Ext.select("a:external");
755
756         * @markdown
757         */
758         pseudos : {
759             "first-child" : function(c){
760                 var r = [], ri = -1, n;
761                 for(var i = 0, ci; ci = n = c[i]; i++){
762                     while((n = n.previousSibling) && n.nodeType != 1);
763                     if(!n){
764                         r[++ri] = ci;
765                     }
766                 }
767                 return r;
768             },
769
770             "last-child" : function(c){
771                 var r = [], ri = -1, n;
772                 for(var i = 0, ci; ci = n = c[i]; i++){
773                     while((n = n.nextSibling) && n.nodeType != 1);
774                     if(!n){
775                         r[++ri] = ci;
776                     }
777                 }
778                 return r;
779             },
780
781             "nth-child" : function(c, a) {
782                 var r = [], ri = -1,
783                     m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a),
784                     f = (m[1] || 1) - 0, l = m[2] - 0;
785                 for(var i = 0, n; n = c[i]; i++){
786                     var pn = n.parentNode;
787                     if (batch != pn._batch) {
788                         var j = 0;
789                         for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
790                             if(cn.nodeType == 1){
791                                cn.nodeIndex = ++j;
792                             }
793                         }
794                         pn._batch = batch;
795                     }
796                     if (f == 1) {
797                         if (l == 0 || n.nodeIndex == l){
798                             r[++ri] = n;
799                         }
800                     } else if ((n.nodeIndex + l) % f == 0){
801                         r[++ri] = n;
802                     }
803                 }
804
805                 return r;
806             },
807
808             "only-child" : function(c){
809                 var r = [], ri = -1;;
810                 for(var i = 0, ci; ci = c[i]; i++){
811                     if(!prev(ci) && !next(ci)){
812                         r[++ri] = ci;
813                     }
814                 }
815                 return r;
816             },
817
818             "empty" : function(c){
819                 var r = [], ri = -1;
820                 for(var i = 0, ci; ci = c[i]; i++){
821                     var cns = ci.childNodes, j = 0, cn, empty = true;
822                     while(cn = cns[j]){
823                         ++j;
824                         if(cn.nodeType == 1 || cn.nodeType == 3){
825                             empty = false;
826                             break;
827                         }
828                     }
829                     if(empty){
830                         r[++ri] = ci;
831                     }
832                 }
833                 return r;
834             },
835
836             "contains" : function(c, v){
837                 var r = [], ri = -1;
838                 for(var i = 0, ci; ci = c[i]; i++){
839                     if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
840                         r[++ri] = ci;
841                     }
842                 }
843                 return r;
844             },
845
846             "nodeValue" : function(c, v){
847                 var r = [], ri = -1;
848                 for(var i = 0, ci; ci = c[i]; i++){
849                     if(ci.firstChild && ci.firstChild.nodeValue == v){
850                         r[++ri] = ci;
851                     }
852                 }
853                 return r;
854             },
855
856             "checked" : function(c){
857                 var r = [], ri = -1;
858                 for(var i = 0, ci; ci = c[i]; i++){
859                     if(ci.checked == true){
860                         r[++ri] = ci;
861                     }
862                 }
863                 return r;
864             },
865
866             "not" : function(c, ss){
867                 return Ext.DomQuery.filter(c, ss, true);
868             },
869
870             "any" : function(c, selectors){
871                 var ss = selectors.split('|'),
872                     r = [], ri = -1, s;
873                 for(var i = 0, ci; ci = c[i]; i++){
874                     for(var j = 0; s = ss[j]; j++){
875                         if(Ext.DomQuery.is(ci, s)){
876                             r[++ri] = ci;
877                             break;
878                         }
879                     }
880                 }
881                 return r;
882             },
883
884             "odd" : function(c){
885                 return this["nth-child"](c, "odd");
886             },
887
888             "even" : function(c){
889                 return this["nth-child"](c, "even");
890             },
891
892             "nth" : function(c, a){
893                 return c[a-1] || [];
894             },
895
896             "first" : function(c){
897                 return c[0] || [];
898             },
899
900             "last" : function(c){
901                 return c[c.length-1] || [];
902             },
903
904             "has" : function(c, ss){
905                 var s = Ext.DomQuery.select,
906                     r = [], ri = -1;
907                 for(var i = 0, ci; ci = c[i]; i++){
908                     if(s(ss, ci).length > 0){
909                         r[++ri] = ci;
910                     }
911                 }
912                 return r;
913             },
914
915             "next" : function(c, ss){
916                 var is = Ext.DomQuery.is,
917                     r = [], ri = -1;
918                 for(var i = 0, ci; ci = c[i]; i++){
919                     var n = next(ci);
920                     if(n && is(n, ss)){
921                         r[++ri] = ci;
922                     }
923                 }
924                 return r;
925             },
926
927             "prev" : function(c, ss){
928                 var is = Ext.DomQuery.is,
929                     r = [], ri = -1;
930                 for(var i = 0, ci; ci = c[i]; i++){
931                     var n = prev(ci);
932                     if(n && is(n, ss)){
933                         r[++ri] = ci;
934                     }
935                 }
936                 return r;
937             }
938         }
939     };
940 }();
941
942 /**
943  * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Ext.DomQuery#select}
944  * @param {String} path The selector/xpath query
945  * @param {Node} root (optional) The start of the query (defaults to document).
946  * @return {Array}
947  * @member Ext
948  * @method query
949  */
950 Ext.query = Ext.DomQuery.select;