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