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