3 * Copyright(c) 2006-2010 Ext JS, Inc.
5 * http://www.extjs.com/license
8 * This is code is also distributed under MIT license for use
9 * with jQuery and prototype JavaScript libraries.
13 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).
15 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>
18 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.
20 <h4>Element Selectors:</h4>
22 <li> <b>*</b> any element</li>
23 <li> <b>E</b> an element with the tag E</li>
24 <li> <b>E F</b> All descendent elements of E that have the tag F</li>
25 <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
26 <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
27 <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
29 <h4>Attribute Selectors:</h4>
30 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
32 <li> <b>E[foo]</b> has an attribute "foo"</li>
33 <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
34 <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
35 <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
36 <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
37 <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
38 <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
40 <h4>Pseudo Classes:</h4>
42 <li> <b>E:first-child</b> E is the first child of its parent</li>
43 <li> <b>E:last-child</b> E is the last child of its parent</li>
44 <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>
45 <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
46 <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
47 <li> <b>E:only-child</b> E is the only child of its parent</li>
48 <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>
49 <li> <b>E:first</b> the first E in the resultset</li>
50 <li> <b>E:last</b> the last E in the resultset</li>
51 <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
52 <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
53 <li> <b>E:even</b> shortcut for :nth-child(even)</li>
54 <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
55 <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
56 <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
57 <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
58 <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
59 <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
60 <li> <b>E:any(S1|S2|S2)</b> an E element which matches any of the simple selectors S1, S2 or S3//\\</li>
62 <h4>CSS Value Selectors:</h4>
64 <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
65 <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
66 <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
67 <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
68 <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
69 <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
73 Ext.DomQuery = function(){
78 trimRe = /^\s+|\s+$/g,
80 modeRe = /^(\s?[\/>+~]\s?|\s|$)/,
81 tagTokenRe = /^(#)?([\w-\*]+)/,
82 nthRe = /(\d*)n\+?(\d*)/,
84 // This is for IE MSXML which does not support expandos.
85 // IE runs the same speed using setAttribute, however FF slows way down
86 // and Safari completely fails so they need to continue to use expandos.
87 isIE = window.ActiveXObject ? true : false,
90 // this eval is stop the compressor from
91 // renaming the variable to something shorter
92 eval("var batch = 30803;");
94 // Retrieve the child node from a particular
95 // parent at the specified index.
96 function child(parent, index){
98 n = parent.firstChild;
110 // retrieve the next element node
112 while((n = n.nextSibling) && n.nodeType != 1);
116 // retrieve the previous element node
118 while((n = n.previousSibling) && n.nodeType != 1);
122 // Mark each child node with a nodeIndex skipping and
123 // removing empty text nodes.
124 function children(parent){
125 var n = parent.firstChild,
129 nextNode = n.nextSibling;
130 // clean worthless empty nodes.
131 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
132 parent.removeChild(n);
134 // add an expando nodeIndex
135 n.nodeIndex = ++nodeIndex;
143 // nodeSet - array of nodes
145 function byClassName(nodeSet, cls){
149 var result = [], ri = -1;
150 for(var i = 0, ci; ci = nodeSet[i]; i++){
151 if((' '+ci.className+' ').indexOf(cls) != -1){
158 function attrValue(n, attr){
159 // if its an array, use the first node.
160 if(!n.tagName && typeof n.length != "undefined"){
170 if(attr == "class" || attr == "className"){
173 return n.getAttribute(attr) || n[attr];
179 // mode - false, /, >, +, ~
180 // tagName - defaults to "*"
181 function getNodes(ns, mode, tagName){
182 var result = [], ri = -1, cs;
186 tagName = tagName || "*";
188 if(typeof ns.getElementsByTagName != "undefined"){
192 // no mode specified, grab all elements by tagName
195 for(var i = 0, ni; ni = ns[i]; i++){
196 cs = ni.getElementsByTagName(tagName);
197 for(var j = 0, ci; ci = cs[j]; j++){
201 // Direct Child mode (/ or >)
202 // E > F or E/F all direct children elements of E that have the tag
203 } else if(mode == "/" || mode == ">"){
204 var utag = tagName.toUpperCase();
205 for(var i = 0, ni, cn; ni = ns[i]; i++){
207 for(var j = 0, cj; cj = cn[j]; j++){
208 if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
213 // Immediately Preceding mode (+)
214 // E + F all elements with the tag F that are immediately preceded by an element with the tag E
215 }else if(mode == "+"){
216 var utag = tagName.toUpperCase();
217 for(var i = 0, n; n = ns[i]; i++){
218 while((n = n.nextSibling) && n.nodeType != 1);
219 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
224 // E ~ F all elements with the tag F that are preceded by a sibling element with the tag E
225 }else if(mode == "~"){
226 var utag = tagName.toUpperCase();
227 for(var i = 0, n; n = ns[i]; i++){
228 while((n = n.nextSibling)){
229 if (n.nodeName == utag || n.nodeName == tagName || tagName == '*'){
238 function concat(a, b){
242 for(var i = 0, l = b.length; i < l; i++){
248 function byTag(cs, tagName){
249 if(cs.tagName || cs == document){
255 var result = [], ri = -1;
256 tagName = tagName.toLowerCase();
257 for(var i = 0, ci; ci = cs[i]; i++){
258 if(ci.nodeType == 1 && ci.tagName.toLowerCase() == tagName){
265 function byId(cs, id){
266 if(cs.tagName || cs == document){
272 var result = [], ri = -1;
273 for(var i = 0, ci; ci = cs[i]; i++){
274 if(ci && ci.id == id){
282 // operators are =, !=, ^=, $=, *=, %=, |= and ~=
284 function byAttribute(cs, attr, value, op, custom){
287 useGetStyle = custom == "{",
288 fn = Ext.DomQuery.operators[op],
293 for(var i = 0, ci; ci = cs[i]; i++){
294 // skip non-element nodes.
295 if(ci.nodeType != 1){
298 // only need to do this for the first node
300 xml = Ext.DomQuery.isXml(ci);
304 // we only need to change the property names if we're dealing with html nodes, not XML
307 a = Ext.DomQuery.getStyle(ci, attr);
308 } else if (attr == "class" || attr == "className"){
310 } else if (attr == "for"){
312 } else if (attr == "href"){
313 // getAttribute href bug
314 // http://www.glennjones.net/Post/809/getAttributehrefbug.htm
315 a = ci.getAttribute("href", 2);
317 a = ci.getAttribute(attr);
320 a = ci.getAttribute(attr);
322 if((fn && fn(a, value)) || (!fn && a)){
329 function byPseudo(cs, name, value){
330 return Ext.DomQuery.pseudos[name](cs, value);
333 function nodupIEXml(cs){
336 cs[0].setAttribute("_nodup", d);
338 for(var i = 1, len = cs.length; i < len; i++){
340 if(!c.getAttribute("_nodup") != d){
341 c.setAttribute("_nodup", d);
345 for(var i = 0, len = cs.length; i < len; i++){
346 cs[i].removeAttribute("_nodup");
355 var len = cs.length, c, i, r = cs, cj, ri = -1;
356 if(!len || typeof cs.nodeType != "undefined" || len == 1){
359 if(isIE && typeof cs[0].selectSingleNode != "undefined"){
360 return nodupIEXml(cs);
364 for(i = 1; c = cs[i]; i++){
369 for(var j = 0; j < i; j++){
372 for(j = i+1; cj = cs[j]; j++){
384 function quickDiffIEXml(c1, c2){
387 for(var i = 0, len = c1.length; i < len; i++){
388 c1[i].setAttribute("_qdiff", d);
390 for(var i = 0, len = c2.length; i < len; i++){
391 if(c2[i].getAttribute("_qdiff") != d){
395 for(var i = 0, len = c1.length; i < len; i++){
396 c1[i].removeAttribute("_qdiff");
401 function quickDiff(c1, c2){
402 var len1 = c1.length,
408 if(isIE && typeof c1[0].selectSingleNode != "undefined"){
409 return quickDiffIEXml(c1, c2);
411 for(var i = 0; i < len1; i++){
414 for(var i = 0, len = c2.length; i < len; i++){
415 if(c2[i]._qdiff != d){
422 function quickId(ns, mode, root, id){
424 var d = root.ownerDocument || root;
425 return d.getElementById(id);
427 ns = getNodes(ns, mode, "*");
432 getStyle : function(el, name){
433 return Ext.fly(el).getStyle(name);
436 * Compiles a selector/xpath query into a reusable function. The returned function
437 * takes one parameter "root" (optional), which is the context node from where the query should start.
438 * @param {String} selector The selector/xpath query
439 * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
442 compile : function(path, type){
443 type = type || "select";
446 var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"],
449 matchers = Ext.DomQuery.matchers,
450 matchersLn = matchers.length,
452 // accept leading mode switch
453 lmode = path.match(modeRe);
455 if(lmode && lmode[1]){
456 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
457 path = path.replace(lmode[1], "");
460 // strip leading slashes
461 while(path.substr(0, 1)=="/"){
462 path = path.substr(1);
465 while(path && lastPath != path){
467 var tokenMatch = path.match(tagTokenRe);
468 if(type == "select"){
471 if(tokenMatch[1] == "#"){
472 fn[fn.length] = 'n = quickId(n, mode, root, "'+tokenMatch[2]+'");';
474 fn[fn.length] = 'n = getNodes(n, mode, "'+tokenMatch[2]+'");';
476 path = path.replace(tokenMatch[0], "");
477 }else if(path.substr(0, 1) != '@'){
478 fn[fn.length] = 'n = getNodes(n, mode, "*");';
483 if(tokenMatch[1] == "#"){
484 fn[fn.length] = 'n = byId(n, "'+tokenMatch[2]+'");';
486 fn[fn.length] = 'n = byTag(n, "'+tokenMatch[2]+'");';
488 path = path.replace(tokenMatch[0], "");
491 while(!(modeMatch = path.match(modeRe))){
493 for(var j = 0; j < matchersLn; j++){
495 var m = path.match(t.re);
497 fn[fn.length] = t.select.replace(tplRe, function(x, i){
500 path = path.replace(m[0], "");
505 // prevent infinite loop on bad selector
507 throw 'Error parsing selector, parsing failed at "' + path + '"';
511 fn[fn.length] = 'mode="'+modeMatch[1].replace(trimRe, "")+'";';
512 path = path.replace(modeMatch[1], "");
516 fn[fn.length] = "return nodup(n);\n}";
518 // eval fn and return it
524 * Selects a group of elements.
525 * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
526 * @param {Node/String} root (optional) The start of the query (defaults to document).
527 * @return {Array} An Array of DOM elements which match the selector. If there are
528 * no matches, and empty Array is returned.
530 jsSelect: function(path, root, type){
531 // set root to doc if not specified.
532 root = root || document;
534 if(typeof root == "string"){
535 root = document.getElementById(root);
537 var paths = path.split(","),
540 // loop over each selector
541 for(var i = 0, len = paths.length; i < len; i++){
542 var subPath = paths[i].replace(trimRe, "");
543 // compile and place in cache
545 cache[subPath] = Ext.DomQuery.compile(subPath);
547 throw subPath + " is not a valid selector";
550 var result = cache[subPath](root);
551 if(result && result != document){
552 results = results.concat(result);
556 // if there were multiple selectors, make sure dups
558 if(paths.length > 1){
559 return nodup(results);
563 isXml: function(el) {
564 var docEl = (el ? el.ownerDocument || el : 0).documentElement;
565 return docEl ? docEl.nodeName !== "HTML" : false;
567 select : document.querySelectorAll ? function(path, root, type) {
568 root = root || document;
569 if (!Ext.DomQuery.isXml(root)) {
571 var cs = root.querySelectorAll(path);
572 return Ext.toArray(cs);
576 return Ext.DomQuery.jsSelect.call(this, path, root, type);
577 } : function(path, root, type) {
578 return Ext.DomQuery.jsSelect.call(this, path, root, type);
582 * Selects a single element.
583 * @param {String} selector The selector/xpath query
584 * @param {Node} root (optional) The start of the query (defaults to document).
585 * @return {Element} The DOM element which matched the selector.
587 selectNode : function(path, root){
588 return Ext.DomQuery.select(path, root)[0];
592 * Selects the value of a node, optionally replacing null with the defaultValue.
593 * @param {String} selector The selector/xpath query
594 * @param {Node} root (optional) The start of the query (defaults to document).
595 * @param {String} defaultValue
598 selectValue : function(path, root, defaultValue){
599 path = path.replace(trimRe, "");
600 if(!valueCache[path]){
601 valueCache[path] = Ext.DomQuery.compile(path, "select");
603 var n = valueCache[path](root), v;
606 // overcome a limitation of maximum textnode size
607 // Rumored to potentially crash IE6 but has not been confirmed.
608 // http://reference.sitepoint.com/javascript/Node/normalize
609 // https://developer.mozilla.org/En/DOM/Node.normalize
610 if (typeof n.normalize == 'function') n.normalize();
612 v = (n && n.firstChild ? n.firstChild.nodeValue : null);
613 return ((v === null||v === undefined||v==='') ? defaultValue : v);
617 * Selects the value of a node, parsing integers and floats. Returns the defaultValue, or 0 if none is specified.
618 * @param {String} selector The selector/xpath query
619 * @param {Node} root (optional) The start of the query (defaults to document).
620 * @param {Number} defaultValue
623 selectNumber : function(path, root, defaultValue){
624 var v = Ext.DomQuery.selectValue(path, root, defaultValue || 0);
625 return parseFloat(v);
629 * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
630 * @param {String/HTMLElement/Array} el An element id, element or array of elements
631 * @param {String} selector The simple selector to test
634 is : function(el, ss){
635 if(typeof el == "string"){
636 el = document.getElementById(el);
638 var isArray = Ext.isArray(el),
639 result = Ext.DomQuery.filter(isArray ? el : [el], ss);
640 return isArray ? (result.length == el.length) : (result.length > 0);
644 * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
645 * @param {Array} el An array of elements to filter
646 * @param {String} selector The simple selector to test
647 * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
648 * the selector instead of the ones that match
649 * @return {Array} An Array of DOM elements which match the selector. If there are
650 * no matches, and empty Array is returned.
652 filter : function(els, ss, nonMatches){
653 ss = ss.replace(trimRe, "");
654 if(!simpleCache[ss]){
655 simpleCache[ss] = Ext.DomQuery.compile(ss, "simple");
657 var result = simpleCache[ss](els);
658 return nonMatches ? quickDiff(result, els) : result;
662 * Collection of matching regular expressions and code snippets.
663 * Each capture group within () will be replace the {} in the select
664 * statement as specified by their index.
668 select: 'n = byClassName(n, " {1} ");'
670 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
671 select: 'n = byPseudo(n, "{1}", "{2}");'
673 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
674 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
677 select: 'n = byId(n, "{1}");'
680 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
685 * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
686 * 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, > <.
689 "=" : function(a, v){
692 "!=" : function(a, v){
695 "^=" : function(a, v){
696 return a && a.substr(0, v.length) == v;
698 "$=" : function(a, v){
699 return a && a.substr(a.length-v.length) == v;
701 "*=" : function(a, v){
702 return a && a.indexOf(v) !== -1;
704 "%=" : function(a, v){
707 "|=" : function(a, v){
708 return a && (a == v || a.substr(0, v.length+1) == v+'-');
710 "~=" : function(a, v){
711 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
716 * <p>Object hash of "pseudo class" filter functions which are used when filtering selections. Each function is passed
717 * two parameters:</p><div class="mdetail-params"><ul>
718 * <li><b>c</b> : Array<div class="sub-desc">An Array of DOM elements to filter.</div></li>
719 * <li><b>v</b> : String<div class="sub-desc">The argument (if any) supplied in the selector.</div></li>
721 * <p>A filter function returns an Array of DOM elements which conform to the pseudo class.</p>
722 * <p>In addition to the provided pseudo classes listed above such as <code>first-child</code> and <code>nth-child</code>,
723 * developers may add additional, custom psuedo class filters to select elements according to application-specific requirements.</p>
724 * <p>For example, to filter <code><a></code> elements to only return links to <i>external</i> resources:</p>
726 Ext.DomQuery.pseudos.external = function(c, v){
728 for(var i = 0, ci; ci = c[i]; i++){
729 // Include in result set only if it's a link to an external resource
730 if(ci.hostname != location.hostname){
736 * Then external links could be gathered with the following statement:<code><pre>
737 var externalLinks = Ext.select("a:external");
741 "first-child" : function(c){
742 var r = [], ri = -1, n;
743 for(var i = 0, ci; ci = n = c[i]; i++){
744 while((n = n.previousSibling) && n.nodeType != 1);
752 "last-child" : function(c){
753 var r = [], ri = -1, n;
754 for(var i = 0, ci; ci = n = c[i]; i++){
755 while((n = n.nextSibling) && n.nodeType != 1);
763 "nth-child" : function(c, a) {
765 m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a),
766 f = (m[1] || 1) - 0, l = m[2] - 0;
767 for(var i = 0, n; n = c[i]; i++){
768 var pn = n.parentNode;
769 if (batch != pn._batch) {
771 for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
772 if(cn.nodeType == 1){
779 if (l == 0 || n.nodeIndex == l){
782 } else if ((n.nodeIndex + l) % f == 0){
790 "only-child" : function(c){
791 var r = [], ri = -1;;
792 for(var i = 0, ci; ci = c[i]; i++){
793 if(!prev(ci) && !next(ci)){
800 "empty" : function(c){
802 for(var i = 0, ci; ci = c[i]; i++){
803 var cns = ci.childNodes, j = 0, cn, empty = true;
806 if(cn.nodeType == 1 || cn.nodeType == 3){
818 "contains" : function(c, v){
820 for(var i = 0, ci; ci = c[i]; i++){
821 if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
828 "nodeValue" : function(c, v){
830 for(var i = 0, ci; ci = c[i]; i++){
831 if(ci.firstChild && ci.firstChild.nodeValue == v){
838 "checked" : function(c){
840 for(var i = 0, ci; ci = c[i]; i++){
841 if(ci.checked == true){
848 "not" : function(c, ss){
849 return Ext.DomQuery.filter(c, ss, true);
852 "any" : function(c, selectors){
853 var ss = selectors.split('|'),
855 for(var i = 0, ci; ci = c[i]; i++){
856 for(var j = 0; s = ss[j]; j++){
857 if(Ext.DomQuery.is(ci, s)){
867 return this["nth-child"](c, "odd");
870 "even" : function(c){
871 return this["nth-child"](c, "even");
874 "nth" : function(c, a){
878 "first" : function(c){
882 "last" : function(c){
883 return c[c.length-1] || [];
886 "has" : function(c, ss){
887 var s = Ext.DomQuery.select,
889 for(var i = 0, ci; ci = c[i]; i++){
890 if(s(ss, ci).length > 0){
897 "next" : function(c, ss){
898 var is = Ext.DomQuery.is,
900 for(var i = 0, ci; ci = c[i]; i++){
909 "prev" : function(c, ss){
910 var is = Ext.DomQuery.is,
912 for(var i = 0, ci; ci = c[i]; i++){
925 * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Ext.DomQuery#select}
926 * @param {String} path The selector/xpath query
927 * @param {Node} root (optional) The start of the query (defaults to document).
932 Ext.query = Ext.DomQuery.select;