De-eval'd selectors and the various DOM methods (will marginally help our speed and...
[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                         var re = quickChild;
122                         var m = re.exec(t);
123
124                         if ( m ) {
125                                 nodeName = m[1].toUpperCase();
126
127                                 // Perform our own iteration and filter
128                                 for ( var i = 0; ret[i]; i++ )
129                                         for ( var c = ret[i].firstChild; c; c = c.nextSibling )
130                                                 if ( c.nodeType == 1 && (nodeName == "*" || c.nodeName.toUpperCase() == nodeName) )
131                                                         r.push( c );
132
133                                 ret = r;
134                                 t = t.replace( re, "" );
135                                 if ( t.indexOf(" ") == 0 ) continue;
136                                 foundToken = true;
137                         } else {
138                                 re = /^([>+~])\s*(\w*)/i;
139
140                                 if ( (m = re.exec(t)) != null ) {
141                                         r = [];
142
143                                         var merge = {};
144                                         nodeName = m[2].toUpperCase();
145                                         m = m[1];
146
147                                         for ( var j = 0, rl = ret.length; j < rl; j++ ) {
148                                                 var n = m == "~" || m == "+" ? ret[j].nextSibling : ret[j].firstChild;
149                                                 for ( ; n; n = n.nextSibling )
150                                                         if ( n.nodeType == 1 ) {
151                                                                 var id = jQuery.data(n);
152
153                                                                 if ( m == "~" && merge[id] ) break;
154                                                                 
155                                                                 if (!nodeName || n.nodeName.toUpperCase() == nodeName ) {
156                                                                         if ( m == "~" ) merge[id] = true;
157                                                                         r.push( n );
158                                                                 }
159                                                                 
160                                                                 if ( m == "+" ) break;
161                                                         }
162                                         }
163
164                                         ret = r;
165
166                                         // And remove the token
167                                         t = jQuery.trim( t.replace( re, "" ) );
168                                         foundToken = true;
169                                 }
170                         }
171
172                         // See if there's still an expression, and that we haven't already
173                         // matched a token
174                         if ( t && !foundToken ) {
175                                 // Handle multiple expressions
176                                 if ( !t.indexOf(",") ) {
177                                         // Clean the result set
178                                         if ( context == ret[0] ) ret.shift();
179
180                                         // Merge the result sets
181                                         done = jQuery.merge( done, ret );
182
183                                         // Reset the context
184                                         r = ret = [context];
185
186                                         // Touch up the selector string
187                                         t = " " + t.substr(1,t.length);
188
189                                 } else {
190                                         // Optimize for the case nodeName#idName
191                                         var re2 = quickID;
192                                         var m = re2.exec(t);
193                                         
194                                         // Re-organize the results, so that they're consistent
195                                         if ( m ) {
196                                                 m = [ 0, m[2], m[3], m[1] ];
197
198                                         } else {
199                                                 // Otherwise, do a traditional filter check for
200                                                 // ID, class, and element selectors
201                                                 re2 = quickClass;
202                                                 m = re2.exec(t);
203                                         }
204
205                                         m[2] = m[2].replace(/\\/g, "");
206
207                                         var elem = ret[ret.length-1];
208
209                                         // Try to do a global search by ID, where we can
210                                         if ( m[1] == "#" && elem && elem.getElementById && !jQuery.isXMLDoc(elem) ) {
211                                                 // Optimization for HTML document case
212                                                 var oid = elem.getElementById(m[2]);
213                                                 
214                                                 // Do a quick check for the existence of the actual ID attribute
215                                                 // to avoid selecting by the name attribute in IE
216                                                 // also check to insure id is a string to avoid selecting an element with the name of 'id' inside a form
217                                                 if ( (jQuery.browser.msie||jQuery.browser.opera) && oid && typeof oid.id == "string" && oid.id != m[2] )
218                                                         oid = jQuery('[@id="'+m[2]+'"]', elem)[0];
219
220                                                 // Do a quick check for node name (where applicable) so
221                                                 // that div#foo searches will be really fast
222                                                 ret = r = oid && (!m[3] || jQuery.nodeName(oid, m[3])) ? [oid] : [];
223                                         } else {
224                                                 // We need to find all descendant elements
225                                                 for ( var i = 0; ret[i]; i++ ) {
226                                                         // Grab the tag name being searched for
227                                                         var tag = m[1] == "#" && m[3] ? m[3] : m[1] != "" || m[0] == "" ? "*" : m[2];
228
229                                                         // Handle IE7 being really dumb about <object>s
230                                                         if ( tag == "*" && ret[i].nodeName.toLowerCase() == "object" )
231                                                                 tag = "param";
232
233                                                         r = jQuery.merge( r, ret[i].getElementsByTagName( tag ));
234                                                 }
235
236                                                 // It's faster to filter by class and be done with it
237                                                 if ( m[1] == "." )
238                                                         r = jQuery.classFilter( r, m[2] );
239
240                                                 // Same with ID filtering
241                                                 if ( m[1] == "#" ) {
242                                                         var tmp = [];
243
244                                                         // Try to find the element with the ID
245                                                         for ( var i = 0; r[i]; i++ )
246                                                                 if ( r[i].getAttribute("id") == m[2] ) {
247                                                                         tmp = [ r[i] ];
248                                                                         break;
249                                                                 }
250
251                                                         r = tmp;
252                                                 }
253
254                                                 ret = r;
255                                         }
256
257                                         t = t.replace( re2, "" );
258                                 }
259
260                         }
261
262                         // If a selector string still exists
263                         if ( t ) {
264                                 // Attempt to filter it
265                                 var val = jQuery.filter(t,r);
266                                 ret = r = val.r;
267                                 t = jQuery.trim(val.t);
268                         }
269                 }
270
271                 // An error occurred with the selector;
272                 // just return an empty set instead
273                 if ( t )
274                         ret = [];
275
276                 // Remove the root context
277                 if ( ret && context == ret[0] )
278                         ret.shift();
279
280                 // And combine the results
281                 done = jQuery.merge( done, ret );
282
283                 return done;
284         },
285
286         classFilter: function(r,m,not){
287                 m = " " + m + " ";
288                 var tmp = [];
289                 for ( var i = 0; r[i]; i++ ) {
290                         var pass = (" " + r[i].className + " ").indexOf( m ) >= 0;
291                         if ( !not && pass || not && !pass )
292                                 tmp.push( r[i] );
293                 }
294                 return tmp;
295         },
296
297         filter: function(t,r,not) {
298                 var last;
299
300                 // Look for common filter expressions
301                 while ( t && t != last ) {
302                         last = t;
303
304                         var p = jQuery.parse, m;
305
306                         for ( var i = 0; p[i]; i++ ) {
307                                 m = p[i].exec( t );
308
309                                 if ( m ) {
310                                         // Remove what we just matched
311                                         t = t.substring( m[0].length );
312
313                                         m[2] = m[2].replace(/\\/g, "");
314                                         break;
315                                 }
316                         }
317
318                         if ( !m )
319                                 break;
320
321                         // :not() is a special case that can be optimized by
322                         // keeping it out of the expression list
323                         if ( m[1] == ":" && m[2] == "not" )
324                                 // optimize if only one selector found (most common case)
325                                 r = isSimple.test( m[3] ) ?
326                                         jQuery.filter(m[3], r, true).r :
327                                         jQuery( r ).not( m[3] );
328
329                         // We can get a big speed boost by filtering by class here
330                         else if ( m[1] == "." )
331                                 r = jQuery.classFilter(r, m[2], not);
332
333                         else if ( m[1] == "[" ) {
334                                 var tmp = [], type = m[3];
335                                 
336                                 for ( var i = 0, rl = r.length; i < rl; i++ ) {
337                                         var a = r[i], z = a[ jQuery.props[m[2]] || m[2] ];
338                                         
339                                         if ( z == null || /href|src|selected/.test(m[2]) )
340                                                 z = jQuery.attr(a,m[2]) || '';
341
342                                         if ( (type == "" && !!z ||
343                                                  type == "=" && z == m[5] ||
344                                                  type == "!=" && z != m[5] ||
345                                                  type == "^=" && z && !z.indexOf(m[5]) ||
346                                                  type == "$=" && z.substr(z.length - m[5].length) == m[5] ||
347                                                  (type == "*=" || type == "~=") && z.indexOf(m[5]) >= 0) ^ not )
348                                                         tmp.push( a );
349                                 }
350                                 
351                                 r = tmp;
352
353                         // We can get a speed boost by handling nth-child here
354                         } else if ( m[1] == ":" && m[2] == "nth-child" ) {
355                                 var merge = {}, tmp = [],
356                                         // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
357                                         test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
358                                                 m[3] == "even" && "2n" || m[3] == "odd" && "2n+1" ||
359                                                 !/\D/.test(m[3]) && "0n+" + m[3] || m[3]),
360                                         // calculate the numbers (first)n+(last) including if they are negative
361                                         first = (test[1] + (test[2] || 1)) - 0, last = test[3] - 0;
362  
363                                 // loop through all the elements left in the jQuery object
364                                 for ( var i = 0, rl = r.length; i < rl; i++ ) {
365                                         var node = r[i], parentNode = node.parentNode, id = jQuery.data(parentNode);
366
367                                         if ( !merge[id] ) {
368                                                 var c = 1;
369
370                                                 for ( var n = parentNode.firstChild; n; n = n.nextSibling )
371                                                         if ( n.nodeType == 1 )
372                                                                 n.nodeIndex = c++;
373
374                                                 merge[id] = true;
375                                         }
376
377                                         var add = false;
378
379                                         if ( first == 0 ) {
380                                                 if ( node.nodeIndex == last )
381                                                         add = true;
382                                         } else if ( (node.nodeIndex - last) % first == 0 && (node.nodeIndex - last) / first >= 0 )
383                                                 add = true;
384
385                                         if ( add ^ not )
386                                                 tmp.push( node );
387                                 }
388
389                                 r = tmp;
390
391                         // Otherwise, find the expression to execute
392                         } else {
393                                 var fn = jQuery.expr[ m[1] ];
394                                 if ( typeof fn == "object" )
395                                         fn = fn[ m[2] ];
396
397                                 if ( typeof fn == "string" )
398                                         fn = eval("false||function(a,i){return " + fn + ";}");
399
400                                 // Execute it against the current filter
401                                 r = jQuery.grep( r, function(elem, i){
402                                         return fn(elem, i, m, r);
403                                 }, not );
404                         }
405                 }
406
407                 // Return an array of filtered elements (r)
408                 // and the modified expression string (t)
409                 return { r: r, t: t };
410         },
411
412         dir: function( elem, dir ){
413                 var matched = [];
414                 var cur = elem[dir];
415                 while ( cur && cur != document ) {
416                         if ( cur.nodeType == 1 )
417                                 matched.push( cur );
418                         cur = cur[dir];
419                 }
420                 return matched;
421         },
422         
423         nth: function(cur,result,dir,elem){
424                 result = result || 1;
425                 var num = 0;
426
427                 for ( ; cur; cur = cur[dir] )
428                         if ( cur.nodeType == 1 && ++num == result )
429                                 break;
430
431                 return cur;
432         },
433         
434         sibling: function( n, elem ) {
435                 var r = [];
436
437                 for ( ; n; n = n.nextSibling ) {
438                         if ( n.nodeType == 1 && (!elem || n != elem) )
439                                 r.push( n );
440                 }
441
442                 return r;
443         }
444 });
445