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