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],
291 for(var i = 0, ci; ci = cs[i]; i++){
292 // skip non-element nodes.
293 if(ci.nodeType != 1){
297 innerHTML = ci.innerHTML;
298 // we only need to change the property names if we're dealing with html nodes, not XML
299 if(innerHTML !== null && innerHTML !== undefined){
301 a = Ext.DomQuery.getStyle(ci, attr);
302 } else if (attr == "class" || attr == "className"){
304 } else if (attr == "for"){
306 } else if (attr == "href"){
307 // getAttribute href bug
308 // http://www.glennjones.net/Post/809/getAttributehrefbug.htm
309 a = ci.getAttribute("href", 2);
311 a = ci.getAttribute(attr);
314 a = ci.getAttribute(attr);
316 if((fn && fn(a, value)) || (!fn && a)){
323 function byPseudo(cs, name, value){
324 return Ext.DomQuery.pseudos[name](cs, value);
327 function nodupIEXml(cs){
330 cs[0].setAttribute("_nodup", d);
332 for(var i = 1, len = cs.length; i < len; i++){
334 if(!c.getAttribute("_nodup") != d){
335 c.setAttribute("_nodup", d);
339 for(var i = 0, len = cs.length; i < len; i++){
340 cs[i].removeAttribute("_nodup");
349 var len = cs.length, c, i, r = cs, cj, ri = -1;
350 if(!len || typeof cs.nodeType != "undefined" || len == 1){
353 if(isIE && typeof cs[0].selectSingleNode != "undefined"){
354 return nodupIEXml(cs);
358 for(i = 1; c = cs[i]; i++){
363 for(var j = 0; j < i; j++){
366 for(j = i+1; cj = cs[j]; j++){
378 function quickDiffIEXml(c1, c2){
381 for(var i = 0, len = c1.length; i < len; i++){
382 c1[i].setAttribute("_qdiff", d);
384 for(var i = 0, len = c2.length; i < len; i++){
385 if(c2[i].getAttribute("_qdiff") != d){
389 for(var i = 0, len = c1.length; i < len; i++){
390 c1[i].removeAttribute("_qdiff");
395 function quickDiff(c1, c2){
396 var len1 = c1.length,
402 if(isIE && typeof c1[0].selectSingleNode != "undefined"){
403 return quickDiffIEXml(c1, c2);
405 for(var i = 0; i < len1; i++){
408 for(var i = 0, len = c2.length; i < len; i++){
409 if(c2[i]._qdiff != d){
416 function quickId(ns, mode, root, id){
418 var d = root.ownerDocument || root;
419 return d.getElementById(id);
421 ns = getNodes(ns, mode, "*");
426 getStyle : function(el, name){
427 return Ext.fly(el).getStyle(name);
430 * Compiles a selector/xpath query into a reusable function. The returned function
431 * takes one parameter "root" (optional), which is the context node from where the query should start.
432 * @param {String} selector The selector/xpath query
433 * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
436 compile : function(path, type){
437 type = type || "select";
440 var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"],
443 matchers = Ext.DomQuery.matchers,
444 matchersLn = matchers.length,
446 // accept leading mode switch
447 lmode = path.match(modeRe);
449 if(lmode && lmode[1]){
450 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
451 path = path.replace(lmode[1], "");
454 // strip leading slashes
455 while(path.substr(0, 1)=="/"){
456 path = path.substr(1);
459 while(path && lastPath != path){
461 var tokenMatch = path.match(tagTokenRe);
462 if(type == "select"){
465 if(tokenMatch[1] == "#"){
466 fn[fn.length] = 'n = quickId(n, mode, root, "'+tokenMatch[2]+'");';
468 fn[fn.length] = 'n = getNodes(n, mode, "'+tokenMatch[2]+'");';
470 path = path.replace(tokenMatch[0], "");
471 }else if(path.substr(0, 1) != '@'){
472 fn[fn.length] = 'n = getNodes(n, mode, "*");';
477 if(tokenMatch[1] == "#"){
478 fn[fn.length] = 'n = byId(n, "'+tokenMatch[2]+'");';
480 fn[fn.length] = 'n = byTag(n, "'+tokenMatch[2]+'");';
482 path = path.replace(tokenMatch[0], "");
485 while(!(modeMatch = path.match(modeRe))){
487 for(var j = 0; j < matchersLn; j++){
489 var m = path.match(t.re);
491 fn[fn.length] = t.select.replace(tplRe, function(x, i){
494 path = path.replace(m[0], "");
499 // prevent infinite loop on bad selector
501 throw 'Error parsing selector, parsing failed at "' + path + '"';
505 fn[fn.length] = 'mode="'+modeMatch[1].replace(trimRe, "")+'";';
506 path = path.replace(modeMatch[1], "");
510 fn[fn.length] = "return nodup(n);\n}";
512 // eval fn and return it
518 * Selects a group of elements.
519 * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
520 * @param {Node/String} root (optional) The start of the query (defaults to document).
521 * @return {Array} An Array of DOM elements which match the selector. If there are
522 * no matches, and empty Array is returned.
524 jsSelect: function(path, root, type){
525 // set root to doc if not specified.
526 root = root || document;
528 if(typeof root == "string"){
529 root = document.getElementById(root);
531 var paths = path.split(","),
534 // loop over each selector
535 for(var i = 0, len = paths.length; i < len; i++){
536 var subPath = paths[i].replace(trimRe, "");
537 // compile and place in cache
539 cache[subPath] = Ext.DomQuery.compile(subPath);
541 throw subPath + " is not a valid selector";
544 var result = cache[subPath](root);
545 if(result && result != document){
546 results = results.concat(result);
550 // if there were multiple selectors, make sure dups
552 if(paths.length > 1){
553 return nodup(results);
557 isXml: function(el) {
558 var docEl = (el ? el.ownerDocument || el : 0).documentElement;
559 return docEl ? docEl.nodeName !== "HTML" : false;
561 select : document.querySelectorAll ? function(path, root, type) {
562 root = root || document;
563 if (!Ext.DomQuery.isXml(root)) {
565 var cs = root.querySelectorAll(path);
566 return Ext.toArray(cs);
570 return Ext.DomQuery.jsSelect.call(this, path, root, type);
571 } : function(path, root, type) {
572 return Ext.DomQuery.jsSelect.call(this, path, root, type);
576 * Selects a single element.
577 * @param {String} selector The selector/xpath query
578 * @param {Node} root (optional) The start of the query (defaults to document).
579 * @return {Element} The DOM element which matched the selector.
581 selectNode : function(path, root){
582 return Ext.DomQuery.select(path, root)[0];
586 * Selects the value of a node, optionally replacing null with the defaultValue.
587 * @param {String} selector The selector/xpath query
588 * @param {Node} root (optional) The start of the query (defaults to document).
589 * @param {String} defaultValue
592 selectValue : function(path, root, defaultValue){
593 path = path.replace(trimRe, "");
594 if(!valueCache[path]){
595 valueCache[path] = Ext.DomQuery.compile(path, "select");
597 var n = valueCache[path](root), v;
600 // overcome a limitation of maximum textnode size
601 // Rumored to potentially crash IE6 but has not been confirmed.
602 // http://reference.sitepoint.com/javascript/Node/normalize
603 // https://developer.mozilla.org/En/DOM/Node.normalize
604 if (typeof n.normalize == 'function') n.normalize();
606 v = (n && n.firstChild ? n.firstChild.nodeValue : null);
607 return ((v === null||v === undefined||v==='') ? defaultValue : v);
611 * Selects the value of a node, parsing integers and floats. Returns the defaultValue, or 0 if none is specified.
612 * @param {String} selector The selector/xpath query
613 * @param {Node} root (optional) The start of the query (defaults to document).
614 * @param {Number} defaultValue
617 selectNumber : function(path, root, defaultValue){
618 var v = Ext.DomQuery.selectValue(path, root, defaultValue || 0);
619 return parseFloat(v);
623 * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
624 * @param {String/HTMLElement/Array} el An element id, element or array of elements
625 * @param {String} selector The simple selector to test
628 is : function(el, ss){
629 if(typeof el == "string"){
630 el = document.getElementById(el);
632 var isArray = Ext.isArray(el),
633 result = Ext.DomQuery.filter(isArray ? el : [el], ss);
634 return isArray ? (result.length == el.length) : (result.length > 0);
638 * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
639 * @param {Array} el An array of elements to filter
640 * @param {String} selector The simple selector to test
641 * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
642 * the selector instead of the ones that match
643 * @return {Array} An Array of DOM elements which match the selector. If there are
644 * no matches, and empty Array is returned.
646 filter : function(els, ss, nonMatches){
647 ss = ss.replace(trimRe, "");
648 if(!simpleCache[ss]){
649 simpleCache[ss] = Ext.DomQuery.compile(ss, "simple");
651 var result = simpleCache[ss](els);
652 return nonMatches ? quickDiff(result, els) : result;
656 * Collection of matching regular expressions and code snippets.
657 * Each capture group within () will be replace the {} in the select
658 * statement as specified by their index.
662 select: 'n = byClassName(n, " {1} ");'
664 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
665 select: 'n = byPseudo(n, "{1}", "{2}");'
667 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
668 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
671 select: 'n = byId(n, "{1}");'
674 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
679 * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
680 * 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, > <.
683 "=" : function(a, v){
686 "!=" : function(a, v){
689 "^=" : function(a, v){
690 return a && a.substr(0, v.length) == v;
692 "$=" : function(a, v){
693 return a && a.substr(a.length-v.length) == v;
695 "*=" : function(a, v){
696 return a && a.indexOf(v) !== -1;
698 "%=" : function(a, v){
701 "|=" : function(a, v){
702 return a && (a == v || a.substr(0, v.length+1) == v+'-');
704 "~=" : function(a, v){
705 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
710 * <p>Object hash of "pseudo class" filter functions which are used when filtering selections. Each function is passed
711 * two parameters:</p><div class="mdetail-params"><ul>
712 * <li><b>c</b> : Array<div class="sub-desc">An Array of DOM elements to filter.</div></li>
713 * <li><b>v</b> : String<div class="sub-desc">The argument (if any) supplied in the selector.</div></li>
715 * <p>A filter function returns an Array of DOM elements which conform to the pseudo class.</p>
716 * <p>In addition to the provided pseudo classes listed above such as <code>first-child</code> and <code>nth-child</code>,
717 * developers may add additional, custom psuedo class filters to select elements according to application-specific requirements.</p>
718 * <p>For example, to filter <code><a></code> elements to only return links to <i>external</i> resources:</p>
720 Ext.DomQuery.pseudos.external = function(c, v){
722 for(var i = 0, ci; ci = c[i]; i++){
723 // Include in result set only if it's a link to an external resource
724 if(ci.hostname != location.hostname){
730 * Then external links could be gathered with the following statement:<code><pre>
731 var externalLinks = Ext.select("a:external");
735 "first-child" : function(c){
736 var r = [], ri = -1, n;
737 for(var i = 0, ci; ci = n = c[i]; i++){
738 while((n = n.previousSibling) && n.nodeType != 1);
746 "last-child" : function(c){
747 var r = [], ri = -1, n;
748 for(var i = 0, ci; ci = n = c[i]; i++){
749 while((n = n.nextSibling) && n.nodeType != 1);
757 "nth-child" : function(c, a) {
759 m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a),
760 f = (m[1] || 1) - 0, l = m[2] - 0;
761 for(var i = 0, n; n = c[i]; i++){
762 var pn = n.parentNode;
763 if (batch != pn._batch) {
765 for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
766 if(cn.nodeType == 1){
773 if (l == 0 || n.nodeIndex == l){
776 } else if ((n.nodeIndex + l) % f == 0){
784 "only-child" : function(c){
785 var r = [], ri = -1;;
786 for(var i = 0, ci; ci = c[i]; i++){
787 if(!prev(ci) && !next(ci)){
794 "empty" : function(c){
796 for(var i = 0, ci; ci = c[i]; i++){
797 var cns = ci.childNodes, j = 0, cn, empty = true;
800 if(cn.nodeType == 1 || cn.nodeType == 3){
812 "contains" : function(c, v){
814 for(var i = 0, ci; ci = c[i]; i++){
815 if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
822 "nodeValue" : function(c, v){
824 for(var i = 0, ci; ci = c[i]; i++){
825 if(ci.firstChild && ci.firstChild.nodeValue == v){
832 "checked" : function(c){
834 for(var i = 0, ci; ci = c[i]; i++){
835 if(ci.checked == true){
842 "not" : function(c, ss){
843 return Ext.DomQuery.filter(c, ss, true);
846 "any" : function(c, selectors){
847 var ss = selectors.split('|'),
849 for(var i = 0, ci; ci = c[i]; i++){
850 for(var j = 0; s = ss[j]; j++){
851 if(Ext.DomQuery.is(ci, s)){
861 return this["nth-child"](c, "odd");
864 "even" : function(c){
865 return this["nth-child"](c, "even");
868 "nth" : function(c, a){
872 "first" : function(c){
876 "last" : function(c){
877 return c[c.length-1] || [];
880 "has" : function(c, ss){
881 var s = Ext.DomQuery.select,
883 for(var i = 0, ci; ci = c[i]; i++){
884 if(s(ss, ci).length > 0){
891 "next" : function(c, ss){
892 var is = Ext.DomQuery.is,
894 for(var i = 0, ci; ci = c[i]; i++){
903 "prev" : function(c, ss){
904 var is = Ext.DomQuery.is,
906 for(var i = 0, ci; ci = c[i]; i++){
919 * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Ext.DomQuery#select}
920 * @param {String} path The selector/xpath query
921 * @param {Node} root (optional) The start of the query (defaults to document).
926 Ext.query = Ext.DomQuery.select;