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