mainly made the code shorter:
[jquery.git] / src / selector.js
1
2 var chars = jQuery.browser.safari && parseInt(jQuery.browser.version) < 417 ?
3                 "(?:[\\w*_-]|\\\\.)" :
4                 "(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",
5         quickChild = new RegExp("^>\\s*(" + chars + "+)"),
6         quickID = new RegExp("^(" + chars + "+)(#)(" + chars + "+)"),
7         quickClass = new RegExp("^([#.]?)(" + chars + "*)");
8
9 jQuery.extend({
10         expr: {
11                 "": function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},
12                 "#": function(a,i,m){return a.getAttribute("id")==m[2];},
13                 ":": {
14                         // Position Checks
15                         lt: function(a,i,m){return i<m[3]-0;},
16                         gt: function(a,i,m){return i>m[3]-0;},
17                         nth: function(a,i,m){return m[3]-0==i;},
18                         eq: function(a,i,m){return m[3]-0==i;},
19                         first: function(a,i){return i==0;},
20                         last: function(a,i,m,r){return i==r.length-1;},
21                         even: function(a,i){return i%2==0;},
22                         odd: function(a,i){return i%2;},
23
24                         // Child Checks
25                         "first-child": function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},
26                         "last-child": function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},
27                         "only-child": function(a){return !jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},
28
29                         // Parent Checks
30                         parent: function(a){return a.firstChild;},
31                         empty: function(a){return !a.firstChild;},
32
33                         // Text Check
34                         contains: function(a,i,m){return (a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},
35
36                         // Visibility
37                         visible: function(a){return "hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},
38                         hidden: function(a){return "hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},
39
40                         // Form attributes
41                         enabled: function(a){return !a.disabled;},
42                         disabled: function(a){return a.disabled;},
43                         checked: function(a){return a.checked;},
44                         selected: function(a){return a.selected||jQuery.attr(a,"selected");},
45
46                         // Form elements
47                         text: function(a){return "text"==a.type;},
48                         radio: function(a){return "radio"==a.type;},
49                         checkbox: function(a){return "checkbox"==a.type;},
50                         file: function(a){return "file"==a.type;},
51                         password: function(a){return "password"==a.type;},
52                         submit: function(a){return "submit"==a.type;},
53                         image: function(a){return "image"==a.type;},
54                         reset: function(a){return "reset"==a.type;},
55                         button: function(a){return "button"==a.type||jQuery.nodeName(a,"button");},
56                         input: function(a){return /input|select|textarea|button/i.test(a.nodeName);},
57
58                         // :has()
59                         has: function(a,i,m){return jQuery.find(m[3],a).length;},
60
61                         // :header
62                         header: function(a){return /h\d/i.test(a.nodeName);},
63
64                         // :animated
65                         animated: function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}
66                 }
67         },
68         
69         // The regular expressions that power the parsing engine
70         parse: [
71                 // Match: [@value='test'], [@foo]
72                 /^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,
73
74                 // Match: :contains('foo')
75                 /^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,
76
77                 // Match: :even, :last-chlid, #id, .class
78                 new RegExp("^([:.#]*)(" + chars + "+)")
79         ],
80
81         multiFilter: function( expr, elems, not ) {
82                 var old, cur = [];
83
84                 while ( expr && expr != old ) {
85                         old = expr;
86                         var f = jQuery.filter( expr, elems, not );
87                         expr = f.t.replace(/^\s*,\s*/, "" );
88                         cur = not ? elems = f.r : jQuery.merge( cur, f.r );
89                 }
90
91                 return cur;
92         },
93
94         find: function( t, context ) {
95                 // Quickly handle non-string expressions
96                 if ( typeof t != "string" )
97                         return [ t ];
98
99                 // check to make sure context is a DOM element or a document
100                 if ( context && context.nodeType != 1 && context.nodeType != 9)
101                         return [ ];
102
103                 // Set the correct context (if none is provided)
104                 context = context || document;
105
106                 // Initialize the search
107                 var ret = [context], done = [], last, nodeName;
108
109                 // Continue while a selector expression exists, and while
110                 // we're no longer looping upon ourselves
111                 while ( t && last != t ) {
112                         var r = [];
113                         last = t;
114
115                         t = jQuery.trim(t);
116
117                         var foundToken = false,
118
119                         // An attempt at speeding up child selectors that
120                         // point to a specific element tag
121                                 re = quickChild,
122                                 
123                                 m = re.exec(t);
124
125                         if ( m ) {
126                                 nodeName = m[1].toUpperCase();
127
128                                 // Perform our own iteration and filter
129                                 for ( var i = 0; ret[i]; i++ )
130                                         for ( var c = ret[i].firstChild; c; c = c.nextSibling )
131                                                 if ( c.nodeType == 1 && (nodeName == "*" || c.nodeName.toUpperCase() == nodeName) )
132                                                         r.push( c );
133
134                                 ret = r;
135                                 t = t.replace( re, "" );
136                                 if ( t.indexOf(" ") == 0 ) continue;
137                                 foundToken = true;
138                         } else {
139                                 re = /^([>+~])\s*(\w*)/i;
140
141                                 if ( (m = re.exec(t)) != null ) {
142                                         r = [];
143
144                                         var merge = {};
145                                         nodeName = m[2].toUpperCase();
146                                         m = m[1];
147
148                                         for ( var j = 0, rl = ret.length; j < rl; j++ ) {
149                                                 var n = m == "~" || m == "+" ? ret[j].nextSibling : ret[j].firstChild;
150                                                 for ( ; n; n = n.nextSibling )
151                                                         if ( n.nodeType == 1 ) {
152                                                                 var id = jQuery.data(n);
153
154                                                                 if ( m == "~" && merge[id] ) break;
155                                                                 
156                                                                 if (!nodeName || n.nodeName.toUpperCase() == nodeName ) {
157                                                                         if ( m == "~" ) merge[id] = true;
158                                                                         r.push( n );
159                                                                 }
160                                                                 
161                                                                 if ( m == "+" ) break;
162                                                         }
163                                         }
164
165                                         ret = r;
166
167                                         // And remove the token
168                                         t = jQuery.trim( t.replace( re, "" ) );
169                                         foundToken = true;
170                                 }
171                         }
172
173                         // See if there's still an expression, and that we haven't already
174                         // matched a token
175                         if ( t && !foundToken ) {
176                                 // Handle multiple expressions
177                                 if ( !t.indexOf(",") ) {
178                                         // Clean the result set
179                                         if ( context == ret[0] ) ret.shift();
180
181                                         // Merge the result sets
182                                         done = jQuery.merge( done, ret );
183
184                                         // Reset the context
185                                         r = ret = [context];
186
187                                         // Touch up the selector string
188                                         t = " " + t.substr(1,t.length);
189
190                                 } else {
191                                         // Optimize for the case nodeName#idName
192                                         var re2 = quickID;
193                                         var m = re2.exec(t);
194                                         
195                                         // Re-organize the results, so that they're consistent
196                                         if ( m ) {
197                                                 m = [ 0, m[2], m[3], m[1] ];
198
199                                         } else {
200                                                 // Otherwise, do a traditional filter check for
201                                                 // ID, class, and element selectors
202                                                 re2 = quickClass;
203                                                 m = re2.exec(t);
204                                         }
205
206                                         m[2] = m[2].replace(/\\/g, "");
207
208                                         var elem = ret[ret.length-1];
209
210                                         // Try to do a global search by ID, where we can
211                                         if ( m[1] == "#" && elem && elem.getElementById && !jQuery.isXMLDoc(elem) ) {
212                                                 // Optimization for HTML document case
213                                                 var oid = elem.getElementById(m[2]);
214                                                 
215                                                 // Do a quick check for the existence of the actual ID attribute
216                                                 // to avoid selecting by the name attribute in IE
217                                                 // also check to insure id is a string to avoid selecting an element with the name of 'id' inside a form
218                                                 if ( (jQuery.browser.msie||jQuery.browser.opera) && oid && typeof oid.id == "string" && oid.id != m[2] )
219                                                         oid = jQuery('[@id="'+m[2]+'"]', elem)[0];
220
221                                                 // Do a quick check for node name (where applicable) so
222                                                 // that div#foo searches will be really fast
223                                                 ret = r = oid && (!m[3] || jQuery.nodeName(oid, m[3])) ? [oid] : [];
224                                         } else {
225                                                 // We need to find all descendant elements
226                                                 for ( var i = 0; ret[i]; i++ ) {
227                                                         // Grab the tag name being searched for
228                                                         var tag = m[1] == "#" && m[3] ? m[3] : m[1] != "" || m[0] == "" ? "*" : m[2];
229
230                                                         // Handle IE7 being really dumb about <object>s
231                                                         if ( tag == "*" && ret[i].nodeName.toLowerCase() == "object" )
232                                                                 tag = "param";
233
234                                                         r = jQuery.merge( r, ret[i].getElementsByTagName( tag ));
235                                                 }
236
237                                                 // It's faster to filter by class and be done with it
238                                                 if ( m[1] == "." )
239                                                         r = jQuery.classFilter( r, m[2] );
240
241                                                 // Same with ID filtering
242                                                 if ( m[1] == "#" ) {
243                                                         var tmp = [];
244
245                                                         // Try to find the element with the ID
246                                                         for ( var i = 0; r[i]; i++ )
247                                                                 if ( r[i].getAttribute("id") == m[2] ) {
248                                                                         tmp = [ r[i] ];
249                                                                         break;
250                                                                 }
251
252                                                         r = tmp;
253                                                 }
254
255                                                 ret = r;
256                                         }
257
258                                         t = t.replace( re2, "" );
259                                 }
260
261                         }
262
263                         // If a selector string still exists
264                         if ( t ) {
265                                 // Attempt to filter it
266                                 var val = jQuery.filter(t,r);
267                                 ret = r = val.r;
268                                 t = jQuery.trim(val.t);
269                         }
270                 }
271
272                 // An error occurred with the selector;
273                 // just return an empty set instead
274                 if ( t )
275                         ret = [];
276
277                 // Remove the root context
278                 if ( ret && context == ret[0] )
279                         ret.shift();
280
281                 // And combine the results
282                 done = jQuery.merge( done, ret );
283
284                 return done;
285         },
286
287         classFilter: function(r,m,not){
288                 m = " " + m + " ";
289                 var tmp = [];
290                 for ( var i = 0; r[i]; i++ ) {
291                         var pass = (" " + r[i].className + " ").indexOf( m ) >= 0;
292                         if ( !not && pass || not && !pass )
293                                 tmp.push( r[i] );
294                 }
295                 return tmp;
296         },
297
298         filter: function(t,r,not) {
299                 var last;
300
301                 // Look for common filter expressions
302                 while ( t && t != last ) {
303                         last = t;
304
305                         var p = jQuery.parse, m;
306
307                         for ( var i = 0; p[i]; i++ ) {
308                                 m = p[i].exec( t );
309
310                                 if ( m ) {
311                                         // Remove what we just matched
312                                         t = t.substring( m[0].length );
313
314                                         m[2] = m[2].replace(/\\/g, "");
315                                         break;
316                                 }
317                         }
318
319                         if ( !m )
320                                 break;
321
322                         // :not() is a special case that can be optimized by
323                         // keeping it out of the expression list
324                         if ( m[1] == ":" && m[2] == "not" )
325                                 // optimize if only one selector found (most common case)
326                                 r = isSimple.test( m[3] ) ?
327                                         jQuery.filter(m[3], r, true).r :
328                                         jQuery( r ).not( m[3] );
329
330                         // We can get a big speed boost by filtering by class here
331                         else if ( m[1] == "." )
332                                 r = jQuery.classFilter(r, m[2], not);
333
334                         else if ( m[1] == "[" ) {
335                                 var type = m[3];
336                                 
337                                 // special case, filter by exact name
338                                 if ( !not && m[2] == 'name' && type == '=' )
339                                         r = jQuery.grep( document.getElementsByName(m[5]), function(elem){
340                                                 return jQuery.inArray( elem, r ) != -1; 
341                                         });
342                                 else {
343                                         for ( var i = 0, rl = r.length, tmp = []; i < rl; i++ ) {
344                                                 var a = r[i], z = a[ jQuery.props[m[2]] || m[2] ];
345                                                 
346                                                 if ( z == null || /href|src|selected/.test(m[2]) )
347                                                         z = jQuery.attr(a,m[2]) || '';
348         
349                                                 if ( (type == "" && !!z ||
350                                                          type == "=" && z == m[5] ||
351                                                          type == "!=" && z != m[5] ||
352                                                          type == "^=" && z && !z.indexOf(m[5]) ||
353                                                          type == "$=" && z.substr(z.length - m[5].length) == m[5] ||
354                                                          (type == "*=" || type == "~=") && z.indexOf(m[5]) >= 0) ^ not )
355                                                                 tmp.push( a );
356                                         }                                       
357                                         r = tmp;
358                                 }
359
360                         // We can get a speed boost by handling nth-child here
361                         } else if ( m[1] == ":" && m[2] == "nth-child" ) {
362                                 var merge = {}, tmp = [],
363                                         // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
364                                         test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
365                                                 m[3] == "even" && "2n" || m[3] == "odd" && "2n+1" ||
366                                                 !/\D/.test(m[3]) && "0n+" + m[3] || m[3]),
367                                         // calculate the numbers (first)n+(last) including if they are negative
368                                         first = (test[1] + (test[2] || 1)) - 0, last = test[3] - 0;
369  
370                                 // loop through all the elements left in the jQuery object
371                                 for ( var i = 0, rl = r.length; i < rl; i++ ) {
372                                         var node = r[i], parentNode = node.parentNode, id = jQuery.data(parentNode);
373
374                                         if ( !merge[id] ) {
375                                                 var c = 1;
376
377                                                 for ( var n = parentNode.firstChild; n; n = n.nextSibling )
378                                                         if ( n.nodeType == 1 )
379                                                                 n.nodeIndex = c++;
380
381                                                 merge[id] = true;
382                                         }
383
384                                         var add = false;
385
386                                         if ( first == 0 ) {
387                                                 if ( node.nodeIndex == last )
388                                                         add = true;
389                                         } else if ( (node.nodeIndex - last) % first == 0 && (node.nodeIndex - last) / first >= 0 )
390                                                 add = true;
391
392                                         if ( add ^ not )
393                                                 tmp.push( node );
394                                 }
395
396                                 r = tmp;
397
398                         // Otherwise, find the expression to execute
399                         } else {
400                                 var fn = jQuery.expr[ m[1] ];
401                                 if ( typeof fn == "object" )
402                                         fn = fn[ m[2] ];
403
404                                 if ( typeof fn == "string" )
405                                         fn = eval("false||function(a,i){return " + fn + ";}");
406
407                                 // Execute it against the current filter
408                                 r = jQuery.grep( r, function(elem, i){
409                                         return fn(elem, i, m, r);
410                                 }, not );
411                         }
412                 }
413
414                 // Return an array of filtered elements (r)
415                 // and the modified expression string (t)
416                 return { r: r, t: t };
417         },
418
419         dir: function( elem, dir ){
420                 var matched = [],
421                         cur = elem[dir];
422                 while ( cur && cur != document ) {
423                         if ( cur.nodeType == 1 )
424                                 matched.push( cur );
425                         cur = cur[dir];
426                 }
427                 return matched;
428         },
429         
430         nth: function(cur,result,dir,elem){
431                 result = result || 1;
432                 var num = 0;
433
434                 for ( ; cur; cur = cur[dir] )
435                         if ( cur.nodeType == 1 && ++num == result )
436                                 break;
437
438                 return cur;
439         },
440         
441         sibling: function( n, elem ) {
442                 var r = [];
443
444                 for ( ; n; n = n.nextSibling ) {
445                         if ( n.nodeType == 1 && (!elem || n != elem) )
446                                 r.push( n );
447                 }
448
449                 return r;
450         }
451 });
452
453