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