2 * This is code is also distributed under MIT license for use
3 * with jQuery and prototype JavaScript libraries.
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).
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>
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.
14 <h4>Element Selectors:</h4>
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>
23 <h4>Attribute Selectors:</h4>
24 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
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>
34 <h4>Pseudo Classes:</h4>
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>
56 <h4>CSS Value Selectors:</h4>
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>
69 Ext.core.DomQuery = Ext.DomQuery = function(){
74 trimRe = /^\s+|\s+$/g,
76 modeRe = /^(\s?[\/>+~]\s?|\s|$)/,
77 tagTokenRe = /^(#)?([\w-\*]+)/,
78 nthRe = /(\d*)n\+?(\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,
86 // this eval is stop the compressor from
87 // renaming the variable to something shorter
88 eval("var batch = 30803;");
90 // Retrieve the child node from a particular
91 // parent at the specified index.
92 function child(parent, index){
94 n = parent.firstChild;
106 // retrieve the next element node
108 while((n = n.nextSibling) && n.nodeType != 1);
112 // retrieve the previous element node
114 while((n = n.previousSibling) && n.nodeType != 1);
118 // Mark each child node with a nodeIndex skipping and
119 // removing empty text nodes.
120 function children(parent){
121 var n = parent.firstChild,
125 nextNode = n.nextSibling;
126 // clean worthless empty nodes.
127 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
128 parent.removeChild(n);
130 // add an expando nodeIndex
131 n.nodeIndex = ++nodeIndex;
139 // nodeSet - array of nodes
141 function byClassName(nodeSet, cls){
145 var result = [], ri = -1;
146 for(var i = 0, ci; ci = nodeSet[i]; i++){
147 if((' '+ci.className+' ').indexOf(cls) != -1){
154 function attrValue(n, attr){
155 // if its an array, use the first node.
156 if(!n.tagName && typeof n.length != "undefined"){
166 if(attr == "class" || attr == "className"){
169 return n.getAttribute(attr) || n[attr];
175 // mode - false, /, >, +, ~
176 // tagName - defaults to "*"
177 function getNodes(ns, mode, tagName){
178 var result = [], ri = -1, cs;
182 tagName = tagName || "*";
184 if(typeof ns.getElementsByTagName != "undefined"){
188 // no mode specified, grab all elements by tagName
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++){
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++){
203 for(var j = 0, cj; cj = cn[j]; j++){
204 if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
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 == '*')){
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 == '*'){
234 function concat(a, b){
238 for(var i = 0, l = b.length; i < l; i++){
244 function byTag(cs, tagName){
245 if(cs.tagName || cs == document){
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){
261 function byId(cs, id){
262 if(cs.tagName || cs == document){
268 var result = [], ri = -1;
269 for(var i = 0, ci; ci = cs[i]; i++){
270 if(ci && ci.id == id){
278 // operators are =, !=, ^=, $=, *=, %=, |= and ~=
280 function byAttribute(cs, attr, value, op, custom){
283 useGetStyle = custom == "{",
284 fn = Ext.DomQuery.operators[op],
289 for(var i = 0, ci; ci = cs[i]; i++){
290 // skip non-element nodes.
291 if(ci.nodeType != 1){
294 // only need to do this for the first node
296 xml = Ext.DomQuery.isXml(ci);
300 // we only need to change the property names if we're dealing with html nodes, not XML
303 a = Ext.DomQuery.getStyle(ci, attr);
304 } else if (attr == "class" || attr == "className"){
306 } else if (attr == "for"){
308 } else if (attr == "href"){
309 // getAttribute href bug
310 // http://www.glennjones.net/Post/809/getAttributehrefbug.htm
311 a = ci.getAttribute("href", 2);
313 a = ci.getAttribute(attr);
316 a = ci.getAttribute(attr);
318 if((fn && fn(a, value)) || (!fn && a)){
325 function byPseudo(cs, name, value){
326 return Ext.DomQuery.pseudos[name](cs, value);
329 function nodupIEXml(cs){
332 cs[0].setAttribute("_nodup", d);
334 for(var i = 1, len = cs.length; i < len; i++){
336 if(!c.getAttribute("_nodup") != d){
337 c.setAttribute("_nodup", d);
341 for(var i = 0, len = cs.length; i < len; i++){
342 cs[i].removeAttribute("_nodup");
351 var len = cs.length, c, i, r = cs, cj, ri = -1;
352 if(!len || typeof cs.nodeType != "undefined" || len == 1){
355 if(isIE && typeof cs[0].selectSingleNode != "undefined"){
356 return nodupIEXml(cs);
360 for(i = 1; c = cs[i]; i++){
365 for(var j = 0; j < i; j++){
368 for(j = i+1; cj = cs[j]; j++){
380 function quickDiffIEXml(c1, c2){
383 for(var i = 0, len = c1.length; i < len; i++){
384 c1[i].setAttribute("_qdiff", d);
386 for(var i = 0, len = c2.length; i < len; i++){
387 if(c2[i].getAttribute("_qdiff") != d){
391 for(var i = 0, len = c1.length; i < len; i++){
392 c1[i].removeAttribute("_qdiff");
397 function quickDiff(c1, c2){
398 var len1 = c1.length,
404 if(isIE && typeof c1[0].selectSingleNode != "undefined"){
405 return quickDiffIEXml(c1, c2);
407 for(var i = 0; i < len1; i++){
410 for(var i = 0, len = c2.length; i < len; i++){
411 if(c2[i]._qdiff != d){
418 function quickId(ns, mode, root, id){
420 var d = root.ownerDocument || root;
421 return d.getElementById(id);
423 ns = getNodes(ns, mode, "*");
428 getStyle : function(el, name){
429 return Ext.fly(el).getStyle(name);
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
438 compile : function(path, type){
439 type = type || "select";
442 var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"],
445 matchers = Ext.DomQuery.matchers,
446 matchersLn = matchers.length,
448 // accept leading mode switch
449 lmode = path.match(modeRe);
451 if(lmode && lmode[1]){
452 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
453 path = path.replace(lmode[1], "");
456 // strip leading slashes
457 while(path.substr(0, 1)=="/"){
458 path = path.substr(1);
461 while(path && lastPath != path){
463 var tokenMatch = path.match(tagTokenRe);
464 if(type == "select"){
467 if(tokenMatch[1] == "#"){
468 fn[fn.length] = 'n = quickId(n, mode, root, "'+tokenMatch[2]+'");';
470 fn[fn.length] = 'n = getNodes(n, mode, "'+tokenMatch[2]+'");';
472 path = path.replace(tokenMatch[0], "");
473 }else if(path.substr(0, 1) != '@'){
474 fn[fn.length] = 'n = getNodes(n, mode, "*");';
479 if(tokenMatch[1] == "#"){
480 fn[fn.length] = 'n = byId(n, "'+tokenMatch[2]+'");';
482 fn[fn.length] = 'n = byTag(n, "'+tokenMatch[2]+'");';
484 path = path.replace(tokenMatch[0], "");
487 while(!(modeMatch = path.match(modeRe))){
489 for(var j = 0; j < matchersLn; j++){
491 var m = path.match(t.re);
493 fn[fn.length] = t.select.replace(tplRe, function(x, i){
496 path = path.replace(m[0], "");
501 // prevent infinite loop on bad selector
505 sourceClass: 'Ext.DomQuery',
506 sourceMethod: 'compile',
507 msg: 'Error parsing selector. Parsing failed at "' + path + '"'
513 fn[fn.length] = 'mode="'+modeMatch[1].replace(trimRe, "")+'";';
514 path = path.replace(modeMatch[1], "");
518 fn[fn.length] = "return nodup(n);\n}";
520 // eval fn and return it
526 * Selects an array of DOM nodes using JavaScript-only implementation.
528 * Use {@link #select} to take advantage of browsers built-in support for CSS selectors.
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.
535 jsSelect: function(path, root, type){
536 // set root to doc if not specified.
537 root = root || document;
539 if(typeof root == "string"){
540 root = document.getElementById(root);
542 var paths = path.split(","),
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
550 cache[subPath] = Ext.DomQuery.compile(subPath);
554 sourceClass: 'Ext.DomQuery',
555 sourceMethod: 'jsSelect',
556 msg: subPath + ' is not a valid selector'
561 var result = cache[subPath](root);
562 if(result && result != document){
563 results = results.concat(result);
567 // if there were multiple selectors, make sure dups
569 if(paths.length > 1){
570 return nodup(results);
575 isXml: function(el) {
576 var docEl = (el ? el.ownerDocument || el : 0).documentElement;
577 return docEl ? docEl.nodeName !== "HTML" : false;
581 * Selects an array of DOM nodes by CSS/XPath selector.
583 * Uses [document.querySelectorAll][0] if browser supports that, otherwise falls back to
584 * {@link #jsSelect} to do the work.
586 * Aliased as {@link Ext#query}.
588 * [0]: https://developer.mozilla.org/en/DOM/document.querySelectorAll
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.
596 select : document.querySelectorAll ? function(path, root, type) {
597 root = root || document;
598 if (!Ext.DomQuery.isXml(root)) {
600 var cs = root.querySelectorAll(path);
601 return Ext.Array.toArray(cs);
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);
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.
616 selectNode : function(path, root){
617 return Ext.DomQuery.select(path, root)[0];
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
627 selectValue : function(path, root, defaultValue){
628 path = path.replace(trimRe, "");
629 if(!valueCache[path]){
630 valueCache[path] = Ext.DomQuery.compile(path, "select");
632 var n = valueCache[path](root), v;
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();
641 v = (n && n.firstChild ? n.firstChild.nodeValue : null);
642 return ((v === null||v === undefined||v==='') ? defaultValue : v);
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
652 selectNumber : function(path, root, defaultValue){
653 var v = Ext.DomQuery.selectValue(path, root, defaultValue || 0);
654 return parseFloat(v);
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
663 is : function(el, ss){
664 if(typeof el == "string"){
665 el = document.getElementById(el);
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);
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.
681 filter : function(els, ss, nonMatches){
682 ss = ss.replace(trimRe, "");
683 if(!simpleCache[ss]){
684 simpleCache[ss] = Ext.DomQuery.compile(ss, "simple");
686 var result = simpleCache[ss](els);
687 return nonMatches ? quickDiff(result, els) : result;
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.
697 select: 'n = byClassName(n, " {1} ");'
699 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
700 select: 'n = byPseudo(n, "{1}", "{2}");'
702 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
703 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
706 select: 'n = byId(n, "{1}");'
709 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
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, > <.
718 "=" : function(a, v){
721 "!=" : function(a, v){
724 "^=" : function(a, v){
725 return a && a.substr(0, v.length) == v;
727 "$=" : function(a, v){
728 return a && a.substr(a.length-v.length) == v;
730 "*=" : function(a, v){
731 return a && a.indexOf(v) !== -1;
733 "%=" : function(a, v){
736 "|=" : function(a, v){
737 return a && (a == v || a.substr(0, v.length+1) == v+'-');
739 "~=" : function(a, v){
740 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
745 Object hash of "pseudo class" filter functions which are used when filtering selections.
746 Each function is passed two parameters:
749 An Array of DOM elements to filter.
752 The argument (if any) supplied in the selector.
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.
758 For example, to filter `a` elements to only return links to __external__ resources:
760 Ext.DomQuery.pseudos.external = function(c, v){
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){
771 Then external links could be gathered with the following statement:
773 var externalLinks = Ext.select("a:external");
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);
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);
800 "nth-child" : function(c, a) {
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) {
808 for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
809 if(cn.nodeType == 1){
816 if (l == 0 || n.nodeIndex == l){
819 } else if ((n.nodeIndex + l) % f == 0){
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)){
837 "empty" : function(c){
839 for(var i = 0, ci; ci = c[i]; i++){
840 var cns = ci.childNodes, j = 0, cn, empty = true;
843 if(cn.nodeType == 1 || cn.nodeType == 3){
855 "contains" : function(c, v){
857 for(var i = 0, ci; ci = c[i]; i++){
858 if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
865 "nodeValue" : function(c, v){
867 for(var i = 0, ci; ci = c[i]; i++){
868 if(ci.firstChild && ci.firstChild.nodeValue == v){
875 "checked" : function(c){
877 for(var i = 0, ci; ci = c[i]; i++){
878 if(ci.checked == true){
885 "not" : function(c, ss){
886 return Ext.DomQuery.filter(c, ss, true);
889 "any" : function(c, selectors){
890 var ss = selectors.split('|'),
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)){
904 return this["nth-child"](c, "odd");
907 "even" : function(c){
908 return this["nth-child"](c, "even");
911 "nth" : function(c, a){
915 "first" : function(c){
919 "last" : function(c){
920 return c[c.length-1] || [];
923 "has" : function(c, ss){
924 var s = Ext.DomQuery.select,
926 for(var i = 0, ci; ci = c[i]; i++){
927 if(s(ss, ci).length > 0){
934 "next" : function(c, ss){
935 var is = Ext.DomQuery.is,
937 for(var i = 0, ci; ci = c[i]; i++){
946 "prev" : function(c, ss){
947 var is = Ext.DomQuery.is,
949 for(var i = 0, ci; ci = c[i]; i++){
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).
969 Ext.query = Ext.DomQuery.select;