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