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