Added support for (basic) nested parens and (basic) nested brackets. You can now...
[jquery.git] / src / selector / selector.js
1 jQuery.extend({
2         expr: {
3                 "": "m[2]== '*'||a.nodeName.toUpperCase()==m[2].toUpperCase()",
4                 "#": "a.getAttribute('id')==m[2]",
5                 ":": {
6                         // Position Checks
7                         lt: "i<m[3]-0",
8                         gt: "i>m[3]-0",
9                         nth: "m[3]-0==i",
10                         eq: "m[3]-0==i",
11                         first: "i==0",
12                         last: "i==r.length-1",
13                         even: "i%2==0",
14                         odd: "i%2",
15
16                         // Child Checks
17                         "nth-child": "jQuery.nth(a.parentNode.firstChild,m[3],'nextSibling')==a",
18                         "first-child": "jQuery.nth(a.parentNode.firstChild,1,'nextSibling')==a",
19                         "last-child": "jQuery.nth(a.parentNode.lastChild,1,'previousSibling')==a",
20                         "only-child": "jQuery.sibling(a.parentNode.firstChild).length==1",
21
22                         // Parent Checks
23                         parent: "a.firstChild",
24                         empty: "!a.firstChild",
25
26                         // Text Check
27                         contains: "jQuery.fn.text.apply([a]).indexOf(m[3])>=0",
28
29                         // Visibility
30                         visible: "a.type!='hidden'&&jQuery.css(a,'display')!='none'&&jQuery.css(a,'visibility')!='hidden'",
31                         hidden: "a.type=='hidden'||jQuery.css(a,'display')=='none'||jQuery.css(a,'visibility')=='hidden'",
32
33                         // Form attributes
34                         enabled: "!a.disabled",
35                         disabled: "a.disabled",
36                         checked: "a.checked",
37                         selected: "a.selected || jQuery.attr(a, 'selected')",
38
39                         // Form elements
40                         text: "a.type=='text'",
41                         radio: "a.type=='radio'",
42                         checkbox: "a.type=='checkbox'",
43                         file: "a.type=='file'",
44                         password: "a.type=='password'",
45                         submit: "a.type=='submit'",
46                         image: "a.type=='image'",
47                         reset: "a.type=='reset'",
48                         button: "a.type=='button'||a.nodeName=='BUTTON'",
49                         input: "/input|select|textarea|button/i.test(a.nodeName)"
50                 },
51                 ".": "jQuery.className.has(a,m[2])",
52                 "@": {
53                         "=": "z==m[4]",
54                         "!=": "z!=m[4]",
55                         "^=": "z && !z.indexOf(m[4])",
56                         "$=": "z && z.substr(z.length - m[4].length,m[4].length)==m[4]",
57                         "*=": "z && z.indexOf(m[4])>=0",
58                         "": "z",
59                         _resort: function(m){
60                                 return ["", m[1], m[3], m[2], m[5]];
61                         },
62                         _prefix: "z=a[m[3]]||jQuery.attr(a,m[3]);"
63                 },
64                 "[": "jQuery.find(m[2],a).length"
65         },
66         
67         // The regular expressions that power the parsing engine
68         parse: [
69                 // Match: [@value='test'], [@foo]
70                 "\\[ *(@)S *([!*$^=]*) *('?\"?)(.*?)\\4 *\\]",
71
72                 // Match: [div], [div p]
73                 "(\\[)\\s*(.*?(\\[.*?\\])?[^[]*?)\\s*\\]",
74
75                 // Match: :contains('foo')
76                 "(:)S\\(\"?'?(.*?(\\(.*?\\))?[^(]*?)\"?'?\\)",
77
78                 // Match: :even, :last-chlid
79                 "([:.#]*)S"
80         ],
81
82         token: [
83                 "\\.\\.|/\\.\\.", "a.parentNode",
84                 ">|/", "jQuery.sibling(a.firstChild)",
85                 "\\+", "jQuery.nth(a,2,'nextSibling')",
86                 "~", function(a){
87                         var s = jQuery.sibling(a.parentNode.firstChild);
88                         return s.slice(0, jQuery.inArray(a,s));
89                 }
90         ],
91
92         /**
93          * @name $.find
94          * @type Array<Element>
95          * @private
96          * @cat Core
97          */
98         find: function( t, context ) {
99                 // Quickly handle non-string expressions
100                 if ( typeof t != "string" )
101                         return [ t ];
102
103                 // Make sure that the context is a DOM Element
104                 if ( context && !context.nodeType )
105                         context = null;
106
107                 // Set the correct context (if none is provided)
108                 context = context || document;
109
110                 // Handle the common XPath // expression
111                 if ( !t.indexOf("//") ) {
112                         context = context.documentElement;
113                         t = t.substr(2,t.length);
114
115                 // And the / root expression
116                 } else if ( !t.indexOf("/") ) {
117                         context = context.documentElement;
118                         t = t.substr(1,t.length);
119                         if ( t.indexOf("/") >= 1 )
120                                 t = t.substr(t.indexOf("/"),t.length);
121                 }
122
123                 // Initialize the search
124                 var ret = [context], done = [], last = null;
125
126                 // Continue while a selector expression exists, and while
127                 // we're no longer looping upon ourselves
128                 while ( t && last != t ) {
129                         var r = [];
130                         last = t;
131
132                         t = jQuery.trim(t).replace( /^\/\//i, "" );
133
134                         var foundToken = false;
135
136                         // An attempt at speeding up child selectors that
137                         // point to a specific element tag
138                         var re = /^[\/>]\s*([a-z0-9*-]+)/i;
139                         var m = re.exec(t);
140
141                         if ( m ) {
142                                 // Perform our own iteration and filter
143                                 for ( var i = 0, rl = ret.length; i < rl; i++ )
144                                         for ( var c = ret[i].firstChild; c; c = c.nextSibling )
145                                                 if ( c.nodeType == 1 && ( c.nodeName == m[1].toUpperCase() || m[1] == "*" ) )
146                                                         r.push( c );
147
148                                 ret = r;
149                                 t = jQuery.trim( t.replace( re, "" ) );
150                                 foundToken = true;
151                         } else {
152                                 // Look for pre-defined expression tokens
153                                 for ( var i = 0; i < jQuery.token.length; i += 2 ) {
154                                         // Attempt to match each, individual, token in
155                                         // the specified order
156                                         var re = new RegExp("^(" + jQuery.token[i] + ")");
157                                         var m = re.exec(t);
158
159                                         // If the token match was found
160                                         if ( m ) {
161                                                 // Map it against the token's handler
162                                                 r = ret = jQuery.map( ret, jQuery.token[i+1].constructor == Function ?
163                                                         jQuery.token[i+1] :
164                                                         function(a){ return eval(jQuery.token[i+1]); });
165
166                                                 // And remove the token
167                                                 t = jQuery.trim( t.replace( re, "" ) );
168                                                 foundToken = true;
169                                                 break;
170                                         }
171                                 }
172                         }
173
174                         // See if there's still an expression, and that we haven't already
175                         // matched a token
176                         if ( t && !foundToken ) {
177                                 // Handle multiple expressions
178                                 if ( !t.indexOf(",") || !t.indexOf("|") ) {
179                                         // Clean teh result set
180                                         if ( ret[0] == context ) ret.shift();
181
182                                         // Merge the result sets
183                                         jQuery.merge( done, ret );
184
185                                         // Reset the context
186                                         r = ret = [context];
187
188                                         // Touch up the selector string
189                                         t = " " + t.substr(1,t.length);
190
191                                 } else {
192                                         // Optomize for the case nodeName#idName
193                                         var re2 = /^([a-z0-9_-]+)(#)([a-z0-9\\*_-]*)/i;
194                                         var m = re2.exec(t);
195                                         
196                                         // Re-organize the results, so that they're consistent
197                                         if ( m ) {
198                                            m = [ 0, m[2], m[3], m[1] ];
199
200                                         } else {
201                                                 // Otherwise, do a traditional filter check for
202                                                 // ID, class, and element selectors
203                                                 re2 = /^([#.]?)([a-z0-9\\*_-]*)/i;
204                                                 m = re2.exec(t);
205                                         }
206
207                                         // Try to do a global search by ID, where we can
208                                         if ( m[1] == "#" && ret[ret.length-1].getElementById ) {
209                                                 // Optimization for HTML document case
210                                                 var oid = ret[ret.length-1].getElementById(m[2]);
211
212                                                 // Do a quick check for node name (where applicable) so
213                                                 // that div#foo searches will be really fast
214                                                 ret = r = oid && 
215                                                   (!m[3] || oid.nodeName == m[3].toUpperCase()) ? [oid] : [];
216
217                                         } else {
218                                                 // Pre-compile a regular expression to handle class searches
219                                                 if ( m[1] == "." )
220                                                         var rec = new RegExp("(^|\\s)" + m[2] + "(\\s|$)");
221
222                                                 // We need to find all descendant elements, it is more
223                                                 // efficient to use getAll() when we are already further down
224                                                 // the tree - we try to recognize that here
225                                                 for ( var i = 0, rl = ret.length; i < rl; i++ )
226                                                         jQuery.merge( r,
227                                                                 m[1] != "" && ret.length != 1 ?
228                                                                         jQuery.getAll( ret[i], [], m[1], m[2], rec ) :
229                                                                         ret[i].getElementsByTagName( m[1] != "" || m[0] == "" ? "*" : m[2] )
230                                                         );
231
232                                                 // It's faster to filter by class and be done with it
233                                                 if ( m[1] == "." && ret.length == 1 )
234                                                         r = jQuery.grep( r, function(e) {
235                                                                 return rec.test(e.className);
236                                                         });
237
238                                                 // Same with ID filtering
239                                                 if ( m[1] == "#" && ret.length == 1 ) {
240                                                         // Remember, then wipe out, the result set
241                                                         var tmp = r;
242                                                         r = [];
243
244                                                         // Then try to find the element with the ID
245                                                         for ( var i = 0, tl = tmp.length; i < tl; i++ )
246                                                                 if ( tmp[i].getAttribute("id") == m[2] ) {
247                                                                         r = [ tmp[i] ];
248                                                                         break;
249                                                                 }
250                                                 }
251
252                                                 ret = r;
253                                         }
254
255                                         t = t.replace( re2, "" );
256                                 }
257
258                         }
259
260                         // If a selector string still exists
261                         if ( t ) {
262                                 // Attempt to filter it
263                                 var val = jQuery.filter(t,r);
264                                 ret = r = val.r;
265                                 t = jQuery.trim(val.t);
266                         }
267                 }
268
269                 // Remove the root context
270                 if ( ret && ret[0] == context ) ret.shift();
271
272                 // And combine the results
273                 jQuery.merge( done, ret );
274
275                 return done;
276         },
277
278         filter: function(t,r,not) {
279                 // Look for common filter expressions
280                 while ( t && /^[a-z[({<*:.#]/i.test(t) ) {
281
282                         var p = jQuery.parse;
283
284                         for ( var i = 0, pl = p.length; i < pl; i++ ) {
285                 
286                                 // Look for, and replace, string-like sequences
287                                 // and finally build a regexp out of it
288                                 var re = new RegExp(
289                                         "^" + p[i].replace("S", "([a-z*_-][a-z0-9_-]*)"), "i" );
290
291                                 var m = re.exec( t );
292
293                                 if ( m ) {
294                                         // Re-organize the first match
295                                         if ( jQuery.expr[ m[1] ]._resort )
296                                                 m = jQuery.expr[ m[1] ]._resort( m );
297
298                                         // Remove what we just matched
299                                         t = t.replace( re, "" );
300
301                                         break;
302                                 }
303                         }
304
305                         // :not() is a special case that can be optimized by
306                         // keeping it out of the expression list
307                         if ( m[1] == ":" && m[2] == "not" )
308                                 r = jQuery.filter(m[3], r, true).r;
309
310                         // Handle classes as a special case (this will help to
311                         // improve the speed, as the regexp will only be compiled once)
312                         else if ( m[1] == "." ) {
313
314                                 var re = new RegExp("(^|\\s)" + m[2] + "(\\s|$)");
315                                 r = jQuery.grep( r, function(e){
316                                         return re.test(e.className || '');
317                                 }, not);
318
319                         // Otherwise, find the expression to execute
320                         } else {
321                                 var f = jQuery.expr[m[1]];
322                                 if ( typeof f != "string" )
323                                         f = jQuery.expr[m[1]][m[2]];
324
325                                 // Build a custom macro to enclose it
326                                 eval("f = function(a,i){" +
327                                         ( jQuery.expr[ m[1] ]._prefix || "" ) +
328                                         "return " + f + "}");
329
330                                 // Execute it against the current filter
331                                 r = jQuery.grep( r, f, not );
332                         }
333                 }
334
335                 // Return an array of filtered elements (r)
336                 // and the modified expression string (t)
337                 return { r: r, t: t };
338         },
339         
340         getAll: function( o, r, token, name, re ) {
341                 for ( var s = o.firstChild; s; s = s.nextSibling )
342                         if ( s.nodeType == 1 ) {
343                                 var add = true;
344
345                                 if ( token == "." )
346                                         add = s.className && re.test(s.className);
347                                 else if ( token == "#" )
348                                         add = s.getAttribute('id') == name;
349         
350                                 if ( add )
351                                         r.push( s );
352
353                                 if ( token == "#" && r.length ) break;
354
355                                 if ( s.firstChild )
356                                         jQuery.getAll( s, r, token, name, re );
357                         }
358
359                 return r;
360         },
361
362         /**
363          * All ancestors of a given element.
364          *
365          * @private
366          * @name $.parents
367          * @type Array<Element>
368          * @param Element elem The element to find the ancestors of.
369          * @cat DOM/Traversing
370          */
371         parents: function( elem ){
372                 var matched = [];
373                 var cur = elem.parentNode;
374                 while ( cur && cur != document ) {
375                         matched.push( cur );
376                         cur = cur.parentNode;
377                 }
378                 return matched;
379         },
380         
381         /**
382          * A handy, and fast, way to traverse in a particular direction and find
383          * a specific element.
384          *
385          * @private
386          * @name $.nth
387          * @type DOMElement
388          * @param DOMElement cur The element to search from.
389          * @param Number|String num The Nth result to match. Can be a number or a string (like 'even' or 'odd').
390          * @param String dir The direction to move in (pass in something like 'previousSibling' or 'nextSibling').
391          * @cat DOM/Traversing
392          */
393         nth: function(cur,result,dir){
394                 result = result || 1;
395                 var num = 0;
396                 for ( ; cur; cur = cur[dir] ) {
397                         if ( cur.nodeType == 1 ) num++;
398                         if ( num == result || result == "even" && num % 2 == 0 && num > 1 ||
399                                 result == "odd" && num % 2 == 1 ) return cur;
400                 }
401         },
402         
403         /**
404          * All elements on a specified axis.
405          *
406          * @private
407          * @name $.sibling
408          * @type Array
409          * @param Element elem The element to find all the siblings of (including itself).
410          * @cat DOM/Traversing
411          */
412         sibling: function( n, elem ) {
413                 var r = [];
414
415                 for ( ; n; n = n.nextSibling ) {
416                         if ( n.nodeType == 1 && (!elem || n != elem) )
417                                 r.push( n );
418                 }
419
420                 return r;
421         }
422 });