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