d7fe9065a0ab6a694dd6d30111d888615e222100
[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                 "[": "parseInt(m[2])?jQuery.nth(a.parentNode.firstChild,parseInt(m[2]),'nextSibling',a)==a: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                 /^\[ *(@)([\w-]+) *([!*$^=]*) *('?"?)(.*?)\4 *\]/,
71
72                 // Match: [div], [div p]
73                 /^(\[)\s*(.*?(\[.*?\])?[^[]*?)\s*\]/,
74
75                 // Match: :contains('foo')
76                 /^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,
77
78                 // Match: :even, :last-chlid, #id, .class
79                 new RegExp("^([:.#]*)(" + 
80                         ( jQuery.chars = "(?:[\\w\u0128-\uFFFF*-]|\\\\.)" ) + "+)")
81         ],
82
83         token: [
84                 /^(\/?\.\.)/, "a.parentNode",
85                 /^(>|\/)/, "jQuery.sibling(a.firstChild)",
86                 /^(\+)/, "jQuery.nth(a,2,'nextSibling')",
87                 /^(~)/, function(a){
88                         var s = jQuery.sibling(a.parentNode.firstChild);
89                         return s.slice(jQuery.inArray(a,s) + 1);
90                 }
91         ],
92
93         multiFilter: function( expr, elems, not ) {
94                 var old, cur = [];
95
96                 while ( expr && expr != old ) {
97                         old = expr;
98                         var f = jQuery.filter( expr, elems, not );
99                         expr = f.t.replace(/^\s*,\s*/, "" );
100                         cur = not ? elems = f.r : jQuery.merge( cur, f.r );
101                 }
102
103                 return cur;
104         },
105
106         /**
107          * @name $.find
108          * @type Array<Element>
109          * @private
110          * @cat Core
111          */
112         find: function( t, context ) {
113                 // Quickly handle non-string expressions
114                 if ( typeof t != "string" )
115                         return [ t ];
116
117                 // Make sure that the context is a DOM Element
118                 if ( context && !context.nodeType )
119                         context = null;
120
121                 // Set the correct context (if none is provided)
122                 context = context || document;
123
124                 // Handle the common XPath // expression
125                 if ( !t.indexOf("//") ) {
126                         context = context.documentElement;
127                         t = t.substr(2,t.length);
128
129                 // And the / root expression
130                 } else if ( !t.indexOf("/") && !context.ownerDocument ) {
131                         context = context.documentElement;
132                         t = t.substr(1,t.length);
133                         if ( t.indexOf("/") >= 1 )
134                                 t = t.substr(t.indexOf("/"),t.length);
135                 }
136
137                 // Initialize the search
138                 var ret = [context], done = [], last;
139
140                 // Continue while a selector expression exists, and while
141                 // we're no longer looping upon ourselves
142                 while ( t && last != t ) {
143                         var r = [];
144                         last = t;
145
146                         t = jQuery.trim(t).replace( /^\/\//, "" );
147
148                         var foundToken = false;
149
150                         // An attempt at speeding up child selectors that
151                         // point to a specific element tag
152                         var re = /^[\/>]\s*([\w*-]+)/;
153                         var m = re.exec(t);
154
155                         if ( m ) {
156                                 // Perform our own iteration and filter
157                                 jQuery.each( ret, function(){
158                                         for ( var c = this.firstChild; c; c = c.nextSibling )
159                                                 if ( c.nodeType == 1 && ( jQuery.nodeName(c, m[1]) || m[1] == "*" ) )
160                                                         r.push( c );
161                                 });
162
163                                 ret = r;
164                                 t = t.replace( re, "" );
165                                 if ( t.indexOf(" ") == 0 ) continue;
166                                 foundToken = true;
167                         } else {
168                                 // Look for pre-defined expression tokens
169                                 for ( var i = 0; i < jQuery.token.length; i += 2 ) {
170                                         // Attempt to match each, individual, token in
171                                         // the specified order
172                                         var re = jQuery.token[i], fn = jQuery.token[i+1];
173                                         var m = re.exec(t);
174
175                                         // If the token match was found
176                                         if ( m ) {
177                                                 // Map it against the token's handler
178                                                 r = ret = jQuery.map( ret, jQuery.isFunction( fn ) ?
179                                                         fn : new Function( "a", "return " + fn ) );
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                                         done = 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 = new RegExp("^(\\w+)(#)(" + jQuery.chars + "+)");
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 = new RegExp("^([#.]?)(" + jQuery.chars + "*)");
219                                                 m = re2.exec(t);
220                                         }
221
222                                         m[2] = m[2].replace(/\\/g, "");
223
224                                         var elem = ret[ret.length-1];
225
226                                         // Try to do a global search by ID, where we can
227                                         if ( m[1] == "#" && elem && elem.getElementById ) {
228                                                 // Optimization for HTML document case
229                                                 var oid = elem.getElementById(m[2]);
230                                                 
231                                                 // Do a quick check for the existence of the actual ID attribute
232                                                 // to avoid selecting by the name attribute in IE
233                                                 if ( (jQuery.browser.msie||jQuery.browser.opera) && oid && oid.id != m[2] )
234                                                         oid = jQuery('[@id="'+m[2]+'"]', elem)[0];
235
236                                                 // Do a quick check for node name (where applicable) so
237                                                 // that div#foo searches will be really fast
238                                                 ret = r = oid && (!m[3] || jQuery.nodeName(oid, m[3])) ? [oid] : [];
239
240                                         } else {
241                                                 // We need to find all descendant elements
242                                                 for ( var i = 0, rl = ret.length; i < rl; i++ ) {
243                                                         // Grab the tag name being searched for
244                                                         var tag = m[1] != "" || m[0] == "" ? "*" : m[2];
245
246                                                         // Handle IE7 being really dumb about <object>s
247                                                         if ( tag == "*" && ret[i].nodeName.toLowerCase() == "object" )
248                                                                 tag = "param";
249
250                                                         r = jQuery.merge( r, ret[i].getElementsByTagName( tag ));
251                                                 }
252
253                                                 // It's faster to filter by class and be done with it
254                                                 if ( m[1] == "." )
255                                                         r = jQuery.grep( r, function(e) {
256                                                                 return jQuery.className.has(e, m[2]);
257                                                         });
258
259                                                 // Same with ID filtering
260                                                 if ( m[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                                                         jQuery.each( tmp, function(){
267                                                                 if ( this.getAttribute("id") == m[2] ) {
268                                                                         r = [ this ];
269                                                                         return false;
270                                                                 }
271                                                         });
272                                                 }
273
274                                                 ret = r;
275                                         }
276
277                                         t = t.replace( re2, "" );
278                                 }
279
280                         }
281
282                         // If a selector string still exists
283                         if ( t ) {
284                                 // Attempt to filter it
285                                 var val = jQuery.filter(t,r);
286                                 ret = r = val.r;
287                                 t = jQuery.trim(val.t);
288                         }
289                 }
290
291                 // An error occurred with the selector;
292                 // just return an empty set instead
293                 if ( t )
294                         ret = [];
295
296                 // Remove the root context
297                 if ( ret && ret[0] == context )
298                         ret.shift();
299
300                 // And combine the results
301                 done = jQuery.merge( done, ret );
302
303                 return done;
304         },
305
306         filter: function(t,r,not) {
307                 var last;
308
309                 // Look for common filter expressions
310                 while ( t  && t != last ) {
311                         last = t;
312
313                         var p = jQuery.parse, m;
314
315                         jQuery.each( p, function(i,re){
316                 
317                                 // Look for, and replace, string-like sequences
318                                 // and finally build a regexp out of it
319                                 m = re.exec( t );
320
321                                 if ( m ) {
322                                         // Remove what we just matched
323                                         t = t.substring( m[0].length );
324
325                                         // Re-organize the first match
326                                         if ( jQuery.expr[ m[1] ]._resort )
327                                                 m = jQuery.expr[ m[1] ]._resort( m );
328
329                                         m[2] = m[2].replace(/\\/g, "");
330
331                                         return false;
332                                 }
333                         });
334
335                         if ( !m )
336                                 continue;
337
338                         // :not() is a special case that can be optimized by
339                         // keeping it out of the expression list
340                         if ( m[1] == ":" && m[2] == "not" )
341                                 r = jQuery.filter(m[3], r, true).r;
342
343                         // Otherwise, find the expression to execute
344                         else {
345                                 var f = jQuery.expr[m[1]];
346                                 if ( typeof f != "string" )
347                                         f = jQuery.expr[m[1]][m[2]];
348
349                                 // Build a custom macro to enclose it
350                                 eval("f = function(a,i){" +
351                                         ( jQuery.expr[ m[1] ]._prefix || "" ) +
352                                         "return " + f + "}");
353
354                                 // Execute it against the current filter
355                                 r = jQuery.grep( r, f, not );
356                         }
357                 }
358
359                 // Return an array of filtered elements (r)
360                 // and the modified expression string (t)
361                 return { r: r, t: t };
362         },
363
364         /**
365          * All ancestors of a given element.
366          *
367          * @private
368          * @name $.parents
369          * @type Array<Element>
370          * @param Element elem The element to find the ancestors of.
371          * @cat DOM/Traversing
372          */
373         parents: function( elem ){
374                 var matched = [];
375                 var cur = elem.parentNode;
376                 while ( cur && cur != document ) {
377                         matched.push( cur );
378                         cur = cur.parentNode;
379                 }
380                 return matched;
381         },
382         
383         /**
384          * A handy, and fast, way to traverse in a particular direction and find
385          * a specific element.
386          *
387          * @private
388          * @name $.nth
389          * @type DOMElement
390          * @param DOMElement cur The element to search from.
391          * @param String|Number num The Nth result to match. Can be a number or a string (like 'even' or 'odd').
392          * @param String dir The direction to move in (pass in something like 'previousSibling' or 'nextSibling').
393          * @cat DOM/Traversing
394          */
395         nth: function(cur,result,dir,elem){
396                 result = result || 1;
397                 var num = 0;
398                 for ( ; cur; cur = cur[dir] ) {
399                         if ( cur.nodeType == 1 ) num++;
400                         if ( num == result || result == "even" && num % 2 == 0 && num > 1 && cur == elem ||
401                                 result == "odd" && num % 2 == 1 && cur == elem ) return cur;
402                 }
403         },
404         
405         /**
406          * All elements on a specified axis.
407          *
408          * @private
409          * @name $.sibling
410          * @type Array
411          * @param Element elem The element to find all the siblings of (including itself).
412          * @cat DOM/Traversing
413          */
414         sibling: function( n, elem ) {
415                 var r = [];
416
417                 for ( ; n; n = n.nextSibling ) {
418                         if ( n.nodeType == 1 && (!elem || n != elem) )
419                                 r.push( n );
420                 }
421
422                 return r;
423         }
424 });