Added minor regexp optimization.
[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         multiFilter: function( expr, elems, not ) {
93                 var old, cur = [];
94
95                 while ( expr && expr != old ) {
96                         old = expr;
97                         var f = jQuery.filter( expr, elems, not );
98                         expr = f.t.replace(/^\s*,\s*/, "" );
99                         cur = not ? elems = f.r : jQuery.merge( cur, f.r );
100                 }
101
102                 return cur;
103         },
104
105         /**
106          * @name $.find
107          * @type Array<Element>
108          * @private
109          * @cat Core
110          */
111         find: function( t, context ) {
112                 // Quickly handle non-string expressions
113                 if ( typeof t != "string" )
114                         return [ t ];
115
116                 // Make sure that the context is a DOM Element
117                 if ( context && !context.nodeType )
118                         context = null;
119
120                 // Set the correct context (if none is provided)
121                 context = context || document;
122
123                 // Handle the common XPath // expression
124                 if ( !t.indexOf("//") ) {
125                         context = context.documentElement;
126                         t = t.substr(2,t.length);
127
128                 // And the / root expression
129                 } else if ( !t.indexOf("/") ) {
130                         context = context.documentElement;
131                         t = t.substr(1,t.length);
132                         if ( t.indexOf("/") >= 1 )
133                                 t = t.substr(t.indexOf("/"),t.length);
134                 }
135
136                 // Initialize the search
137                 var ret = [context], done = [], last = null;
138
139                 // Continue while a selector expression exists, and while
140                 // we're no longer looping upon ourselves
141                 while ( t && last != t ) {
142                         var r = [];
143                         last = t;
144
145                         t = jQuery.trim(t).replace( /^\/\//i, "" );
146
147                         var foundToken = false;
148
149                         // An attempt at speeding up child selectors that
150                         // point to a specific element tag
151                         var re = /^[\/>]\s*([a-z0-9*-]+)/i;
152                         var m = re.exec(t);
153
154                         if ( m ) {
155                                 // Perform our own iteration and filter
156                                 for ( var i = 0, rl = ret.length; i < rl; i++ )
157                                         for ( var c = ret[i].firstChild; c; c = c.nextSibling )
158                                                 if ( c.nodeType == 1 && ( c.nodeName == m[1].toUpperCase() || m[1] == "*" ) )
159                                                         r.push( c );
160
161                                 ret = r;
162                                 t = jQuery.trim( t.replace( re, "" ) );
163                                 foundToken = true;
164                         } else {
165                                 // Look for pre-defined expression tokens
166                                 for ( var i = 0; i < jQuery.token.length; i += 2 ) {
167                                         // Attempt to match each, individual, token in
168                                         // the specified order
169                                         var re = new RegExp("^(" + jQuery.token[i] + ")");
170                                         var m = re.exec(t);
171
172                                         // If the token match was found
173                                         if ( m ) {
174                                                 // Map it against the token's handler
175                                                 r = ret = jQuery.map( ret, jQuery.token[i+1].constructor == Function ?
176                                                         jQuery.token[i+1] :
177                                                         function(a){ return eval(jQuery.token[i+1]); });
178
179                                                 // And remove the token
180                                                 t = jQuery.trim( t.replace( re, "" ) );
181                                                 foundToken = true;
182                                                 break;
183                                         }
184                                 }
185                         }
186
187                         // See if there's still an expression, and that we haven't already
188                         // matched a token
189                         if ( t && !foundToken ) {
190                                 // Handle multiple expressions
191                                 if ( !t.indexOf(",") ) {
192                                         // Clean the result set
193                                         if ( ret[0] == context ) ret.shift();
194
195                                         // Merge the result sets
196                                         jQuery.merge( done, ret );
197
198                                         // Reset the context
199                                         r = ret = [context];
200
201                                         // Touch up the selector string
202                                         t = " " + t.substr(1,t.length);
203
204                                 } else {
205                                         // Optomize for the case nodeName#idName
206                                         var re2 = /^([a-z0-9_-]+)(#)([a-z0-9\\*_-]*)/i;
207                                         var m = re2.exec(t);
208                                         
209                                         // Re-organize the results, so that they're consistent
210                                         if ( m ) {
211                                            m = [ 0, m[2], m[3], m[1] ];
212
213                                         } else {
214                                                 // Otherwise, do a traditional filter check for
215                                                 // ID, class, and element selectors
216                                                 re2 = /^([#.]?)([a-z0-9\\*_-]*)/i;
217                                                 m = re2.exec(t);
218                                         }
219
220                                         // Try to do a global search by ID, where we can
221                                         if ( m[1] == "#" && ret[ret.length-1].getElementById ) {
222                                                 // Optimization for HTML document case
223                                                 var oid = ret[ret.length-1].getElementById(m[2]);
224
225                                                 // Do a quick check for node name (where applicable) so
226                                                 // that div#foo searches will be really fast
227                                                 ret = r = oid && 
228                                                   (!m[3] || oid.nodeName == m[3].toUpperCase()) ? [oid] : [];
229
230                                         } else {
231                                                 // Pre-compile a regular expression to handle class searches
232                                                 if ( m[1] == "." )
233                                                         var rec = new RegExp("(^|\\s)" + m[2] + "(\\s|$)");
234
235                                                 // We need to find all descendant elements, it is more
236                                                 // efficient to use getAll() when we are already further down
237                                                 // the tree - we try to recognize that here
238                                                 for ( var i = 0, rl = ret.length; i < rl; i++ ) {
239                                                         // Grab the tag name being searched for
240                                                         var tag = m[1] != "" || m[0] == "" ? "*" : m[2];
241
242                                                         // Handle IE7 being really dumb about <object>s
243                                                         if ( ret[i].nodeName.toUpperCase() == "OBJECT" && tag == "*" )
244                                                                 tag = "param";
245
246                                                         jQuery.merge( r,
247                                                                 m[1] != "" && ret.length != 1 ?
248                                                                         jQuery.getAll( ret[i], [], m[1], m[2], rec ) :
249                                                                         ret[i].getElementsByTagName( tag )
250                                                         );
251                                                 }
252
253                                                 // It's faster to filter by class and be done with it
254                                                 if ( m[1] == "." && ret.length == 1 )
255                                                         r = jQuery.grep( r, function(e) {
256                                                                 return rec.test(e.className);
257                                                         });
258
259                                                 // Same with ID filtering
260                                                 if ( m[1] == "#" && ret.length == 1 ) {
261                                                         // Remember, then wipe out, the result set
262                                                         var tmp = r;
263                                                         r = [];
264
265                                                         // Then try to find the element with the ID
266                                                         for ( var i = 0, tl = tmp.length; i < tl; i++ )
267                                                                 if ( tmp[i].getAttribute("id") == m[2] ) {
268                                                                         r = [ tmp[i] ];
269                                                                         break;
270                                                                 }
271                                                 }
272
273                                                 ret = r;
274                                         }
275
276                                         t = t.replace( re2, "" );
277                                 }
278
279                         }
280
281                         // If a selector string still exists
282                         if ( t ) {
283                                 // Attempt to filter it
284                                 var val = jQuery.filter(t,r);
285                                 ret = r = val.r;
286                                 t = jQuery.trim(val.t);
287                         }
288                 }
289
290                 // Remove the root context
291                 if ( ret && ret[0] == context ) ret.shift();
292
293                 // And combine the results
294                 jQuery.merge( done, ret );
295
296                 return done;
297         },
298
299         filter: function(t,r,not) {
300                 // Look for common filter expressions
301                 while ( t && /^[a-z[({<*:.#]/i.test(t) ) {
302
303                         var p = jQuery.parse;
304
305                         for ( var i = 0, pl = p.length; i < pl; i++ ) {
306                 
307                                 // Look for, and replace, string-like sequences
308                                 // and finally build a regexp out of it
309                                 var re = new RegExp(
310                                         "^" + p[i].replace("S", "([a-z*_-][a-z0-9_-]*)"), "i" );
311
312                                 var m = re.exec( t );
313
314                                 if ( m ) {
315                                         // Remove what we just matched
316                                         t = t.substring( m[0].length );
317
318                                         // Re-organize the first match
319                                         if ( jQuery.expr[ m[1] ]._resort )
320                                                 m = jQuery.expr[ m[1] ]._resort( m );
321
322                                         break;
323                                 }
324                         }
325
326                         // :not() is a special case that can be optimized by
327                         // keeping it out of the expression list
328                         if ( m[1] == ":" && m[2] == "not" )
329                                 r = jQuery.filter(m[3], r, true).r;
330
331                         // Handle classes as a special case (this will help to
332                         // improve the speed, as the regexp will only be compiled once)
333                         else if ( m[1] == "." ) {
334
335                                 var re = new RegExp("(^|\\s)" + m[2] + "(\\s|$)");
336                                 r = jQuery.grep( r, function(e){
337                                         return re.test(e.className || '');
338                                 }, not);
339
340                         // Otherwise, find the expression to execute
341                         } else {
342                                 var f = jQuery.expr[m[1]];
343                                 if ( typeof f != "string" )
344                                         f = jQuery.expr[m[1]][m[2]];
345
346                                 // Build a custom macro to enclose it
347                                 eval("f = function(a,i){" +
348                                         ( jQuery.expr[ m[1] ]._prefix || "" ) +
349                                         "return " + f + "}");
350
351                                 // Execute it against the current filter
352                                 r = jQuery.grep( r, f, not );
353                         }
354                 }
355
356                 // Return an array of filtered elements (r)
357                 // and the modified expression string (t)
358                 return { r: r, t: t };
359         },
360         
361         getAll: function( o, r, token, name, re ) {
362                 for ( var s = o.firstChild; s; s = s.nextSibling )
363                         if ( s.nodeType == 1 ) {
364                                 var add = true;
365
366                                 if ( token == "." )
367                                         add = s.className && re.test(s.className);
368                                 else if ( token == "#" )
369                                         add = s.getAttribute('id') == name;
370         
371                                 if ( add )
372                                         r.push( s );
373
374                                 if ( token == "#" && r.length ) break;
375
376                                 if ( s.firstChild )
377                                         jQuery.getAll( s, r, token, name, re );
378                         }
379
380                 return r;
381         },
382
383         /**
384          * All ancestors of a given element.
385          *
386          * @private
387          * @name $.parents
388          * @type Array<Element>
389          * @param Element elem The element to find the ancestors of.
390          * @cat DOM/Traversing
391          */
392         parents: function( elem ){
393                 var matched = [];
394                 var cur = elem.parentNode;
395                 while ( cur && cur != document ) {
396                         matched.push( cur );
397                         cur = cur.parentNode;
398                 }
399                 return matched;
400         },
401         
402         /**
403          * A handy, and fast, way to traverse in a particular direction and find
404          * a specific element.
405          *
406          * @private
407          * @name $.nth
408          * @type DOMElement
409          * @param DOMElement cur The element to search from.
410          * @param Number|String num The Nth result to match. Can be a number or a string (like 'even' or 'odd').
411          * @param String dir The direction to move in (pass in something like 'previousSibling' or 'nextSibling').
412          * @cat DOM/Traversing
413          */
414         nth: function(cur,result,dir){
415                 result = result || 1;
416                 var num = 0;
417                 for ( ; cur; cur = cur[dir] ) {
418                         if ( cur.nodeType == 1 ) num++;
419                         if ( num == result || result == "even" && num % 2 == 0 && num > 1 ||
420                                 result == "odd" && num % 2 == 1 ) return cur;
421                 }
422         },
423         
424         /**
425          * All elements on a specified axis.
426          *
427          * @private
428          * @name $.sibling
429          * @type Array
430          * @param Element elem The element to find all the siblings of (including itself).
431          * @cat DOM/Traversing
432          */
433         sibling: function( n, elem ) {
434                 var r = [];
435
436                 for ( ; n; n = n.nextSibling ) {
437                         if ( n.nodeType == 1 && (!elem || n != elem) )
438                                 r.push( n );
439                 }
440
441                 return r;
442         }
443 });