Added .prevAll() and .nextAll() functionality.
[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||'').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                 // Make sure that the context is a DOM Element
100                 if ( context && !context.nodeType )
101                         context = null;
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;
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                                 var 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.toUpperCase()) )
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 nodeName = m[2], 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.toUpperCase() ) {
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                                 r = jQuery.filter(m[3], r, true).r;
324
325                         // We can get a big speed boost by filtering by class here
326                         else if ( m[1] == "." )
327                                 r = jQuery.classFilter(r, m[2], not);
328
329                         else if ( m[1] == "[" ) {
330                                 var tmp = [], type = m[3];
331                                 
332                                 for ( var i = 0, rl = r.length; i < rl; i++ ) {
333                                         var a = r[i], z = a[ jQuery.props[m[2]] || m[2] ];
334                                         
335                                         if ( z == null || /href|src|selected/.test(m[2]) )
336                                                 z = jQuery.attr(a,m[2]) || '';
337
338                                         if ( (type == "" && !!z ||
339                                                  type == "=" && z == m[5] ||
340                                                  type == "!=" && z != m[5] ||
341                                                  type == "^=" && z && !z.indexOf(m[5]) ||
342                                                  type == "$=" && z.substr(z.length - m[5].length) == m[5] ||
343                                                  (type == "*=" || type == "~=") && z.indexOf(m[5]) >= 0) ^ not )
344                                                         tmp.push( a );
345                                 }
346                                 
347                                 r = tmp;
348
349                         // We can get a speed boost by handling nth-child here
350                         } else if ( m[1] == ":" && m[2] == "nth-child" ) {
351                                 var merge = {}, tmp = [],
352                                         test = /(\d*)n\+?(\d*)/.exec(
353                                                 m[3] == "even" && "2n" || m[3] == "odd" && "2n+1" ||
354                                                 !/\D/.test(m[3]) && "n+" + m[3] || m[3]),
355                                         first = (test[1] || 1) - 0, last = test[2] - 0;
356
357                                 for ( var i = 0, rl = r.length; i < rl; i++ ) {
358                                         var node = r[i], parentNode = node.parentNode, id = jQuery.data(parentNode);
359
360                                         if ( !merge[id] ) {
361                                                 var c = 1;
362
363                                                 for ( var n = parentNode.firstChild; n; n = n.nextSibling )
364                                                         if ( n.nodeType == 1 )
365                                                                 n.nodeIndex = c++;
366
367                                                 merge[id] = true;
368                                         }
369
370                                         var add = false;
371
372                                         if ( first == 1 ) {
373                                                 if ( last == 0 || node.nodeIndex == last )
374                                                         add = true;
375                                         } else if ( (node.nodeIndex + last) % first == 0 )
376                                                 add = true;
377
378                                         if ( add ^ not )
379                                                 tmp.push( node );
380                                 }
381
382                                 r = tmp;
383
384                         // Otherwise, find the expression to execute
385                         } else {
386                                 var f = jQuery.expr[m[1]];
387                                 if ( typeof f != "string" )
388                                         f = jQuery.expr[m[1]][m[2]];
389
390                                 // Build a custom macro to enclose it
391                                 f = eval("false||function(a,i){return " + f + "}");
392
393                                 // Execute it against the current filter
394                                 r = jQuery.grep( r, f, not );
395                         }
396                 }
397
398                 // Return an array of filtered elements (r)
399                 // and the modified expression string (t)
400                 return { r: r, t: t };
401         },
402
403         dir: function( elem, dir ){
404                 var matched = [];
405                 var cur = elem[dir];
406                 while ( cur && cur != document ) {
407                         matched.push( cur );
408                         cur = cur[dir];
409                 }
410                 return matched;
411         },
412         
413         nth: function(cur,result,dir,elem){
414                 result = result || 1;
415                 var num = 0;
416
417                 for ( ; cur; cur = cur[dir] )
418                         if ( cur.nodeType == 1 && ++num == result )
419                                 break;
420
421                 return cur;
422         },
423         
424         sibling: function( n, elem ) {
425                 var r = [];
426
427                 for ( ; n; n = n.nextSibling ) {
428                         if ( n.nodeType == 1 && (!elem || n != elem) )
429                                 r.push( n );
430                 }
431
432                 return r;
433         }
434 });