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