Optimize jQuery() for the case $("TAG").
[jquery.git] / src / core.js
1 // Define a local copy of jQuery
2 var jQuery = function( selector, context ) {
3                 // The jQuery object is actually just the init constructor 'enhanced'
4                 return arguments.length === 0 ?
5                         rootjQuery :
6                         new jQuery.fn.init( selector, context );
7         },
8
9         // Map over jQuery in case of overwrite
10         _jQuery = window.jQuery,
11
12         // Map over the $ in case of overwrite
13         _$ = window.$,
14
15         // Use the correct document accordingly with window argument (sandbox)
16         document = window.document,
17
18         // A central reference to the root jQuery(document)
19         rootjQuery,
20
21         // A simple way to check for HTML strings or ID strings
22         // (both of which we optimize for)
23         quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,
24
25         // Is it a simple selector
26         isSimple = /^.[^:#\[\.,]*$/,
27
28         // Check if a string has a non-whitespace character in it
29         rnotwhite = /\S/,
30
31         // Used for trimming whitespace
32         rtrim = /^\s+|\s+$/g,
33
34         // Match a standalone tag
35         rsingleTag = /^<(\w+)\s*\/?>$/,
36
37         // Keep a UserAgent string for use with jQuery.browser
38         userAgent = navigator.userAgent.toLowerCase(),
39
40         // Save a reference to some core methods
41         toString = Object.prototype.toString,
42         push = Array.prototype.push,
43         slice = Array.prototype.slice,
44         indexOf = Array.prototype.indexOf;
45
46 jQuery.fn = jQuery.prototype = {
47         init: function( selector, context ) {
48                 var match, elem, ret, doc;
49
50                 // Handle $(""), $(null), or $(undefined)
51                 if ( !selector ) {
52                         return this;
53                 }
54
55                 // $("body"): Shortcut for quickly finding the body element
56                 if ( selector === "body" && !context && document.body ) {
57                         selector = document.body;
58                 }
59
60                 // Handle $(DOMElement)
61                 if ( selector.nodeType ) {
62                         this.context = this[0] = selector;
63                         this.length++;
64                         return this;
65                 }
66
67                 // Handle HTML strings
68                 if ( typeof selector === "string" ) {
69                         // Are we dealing with HTML string or an ID?
70                         match = quickExpr.exec( selector );
71
72                         // Verify a match, and that no context was specified for #id
73                         if ( match && (match[1] || !context) ) {
74
75                                 // HANDLE: $(html) -> $(array)
76                                 if ( match[1] ) {
77                                         doc = (context ? context.ownerDocument || context : document);
78
79                                         // If a single string is passed in and it's a single tag
80                                         // just do a createElement and skip the rest
81                                         ret = rsingleTag.exec( selector );
82
83                                         if ( ret ) {
84                                                 selector = [ doc.createElement( ret[1] ) ];
85
86                                         } else {
87                                                 ret = buildFragment( [ match[1] ], [ doc ] );
88                                                 selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes;
89                                         }
90
91                                 // HANDLE: $("#id")
92                                 } else {
93                                         elem = document.getElementById( match[2] );
94
95                                         if ( elem ) {
96                                                 // Handle the case where IE and Opera return items
97                                                 // by name instead of ID
98                                                 if ( elem.id !== match[2] ) {
99                                                         return rootjQuery.find( selector );
100                                                 }
101
102                                                 // Otherwise, we inject the element directly into the jQuery object
103                                                 this.length++;
104                                                 this[0] = elem;
105                                         }
106
107                                         this.context = document;
108                                         this.selector = selector;
109                                         return this;
110                                 }
111
112                         // HANDLE: $("TAG")
113                         } else if ( !context && /^\w+$/.test( selector ) ) {
114                                 selector = document.getElementsByTagName( selector );
115
116                         // HANDLE: $(expr, $(...))
117                         } else if ( !context || context.jquery ) {
118                                 return (context || rootjQuery).find( selector );
119
120                         // HANDLE: $(expr, context)
121                         // (which is just equivalent to: $(context).find(expr)
122                         } else {
123                                 return jQuery( context ).find( selector );
124                         }
125
126                 // HANDLE: $(function)
127                 // Shortcut for document ready
128                 } else if ( jQuery.isFunction( selector ) ) {
129                         return rootjQuery.ready( selector );
130                 }
131
132                 // Make sure that old selector state is passed along
133                 if ( selector.selector && selector.context ) {
134                         this.selector = selector.selector;
135                         this.context = selector.context;
136                 }
137
138                 return this.setArray(jQuery.isArray( selector ) ?
139                         selector :
140                         jQuery.makeArray(selector));
141         },
142
143         // Start with an empty selector
144         selector: "",
145
146         // The current version of jQuery being used
147         jquery: "@VERSION",
148
149         // The default length of a jQuery object is 0
150         length: 0,
151
152         // The number of elements contained in the matched element set
153         size: function() {
154                 return this.length;
155         },
156
157         toArray: function(){
158                 return slice.call( this, 0 );
159         },
160
161         // Get the Nth element in the matched element set OR
162         // Get the whole matched element set as a clean array
163         get: function( num ) {
164                 return num == null ?
165
166                         // Return a 'clean' array
167                         this.toArray() :
168
169                         // Return just the object
170                         ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
171         },
172
173         // Take an array of elements and push it onto the stack
174         // (returning the new matched element set)
175         pushStack: function( elems, name, selector ) {
176                 // Build a new jQuery matched element set
177                 var ret = jQuery( elems || null );
178
179                 // Add the old object onto the stack (as a reference)
180                 ret.prevObject = this;
181
182                 ret.context = this.context;
183
184                 if ( name === "find" ) {
185                         ret.selector = this.selector + (this.selector ? " " : "") + selector;
186                 } else if ( name ) {
187                         ret.selector = this.selector + "." + name + "(" + selector + ")";
188                 }
189
190                 // Return the newly-formed element set
191                 return ret;
192         },
193
194         // Force the current matched set of elements to become
195         // the specified array of elements (destroying the stack in the process)
196         // You should use pushStack() in order to do this, but maintain the stack
197         setArray: function( elems ) {
198                 // Resetting the length to 0, then using the native Array push
199                 // is a super-fast way to populate an object with array-like properties
200                 this.length = 0;
201                 push.apply( this, elems );
202
203                 return this;
204         },
205
206         // Execute a callback for every element in the matched set.
207         // (You can seed the arguments with an array of args, but this is
208         // only used internally.)
209         each: function( callback, args ) {
210                 return jQuery.each( this, callback, args );
211         },
212
213         // Determine the position of an element within
214         // the matched set of elements
215         index: function( elem ) {
216                 if ( !elem || typeof elem === "string" ) {
217                         return jQuery.inArray( this[0],
218                                 // If it receives a string, the selector is used
219                                 // If it receives nothing, the siblings are used
220                                 elem ? jQuery( elem ) : this.parent().children() );
221                 }
222                 // Locate the position of the desired element
223                 return jQuery.inArray(
224                         // If it receives a jQuery object, the first element is used
225                         elem.jquery ? elem[0] : elem, this );
226         },
227
228         is: function( selector ) {
229                 return !!selector && jQuery.multiFilter( selector, this ).length > 0;
230         },
231
232         // For internal use only.
233         // Behaves like an Array's method, not like a jQuery method.
234         push: push,
235         sort: [].sort,
236         splice: [].splice
237 };
238
239 // Give the init function the jQuery prototype for later instantiation
240 jQuery.fn.init.prototype = jQuery.fn;
241
242 jQuery.extend = jQuery.fn.extend = function() {
243         // copy reference to target object
244         var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;
245
246         // Handle a deep copy situation
247         if ( typeof target === "boolean" ) {
248                 deep = target;
249                 target = arguments[1] || {};
250                 // skip the boolean and the target
251                 i = 2;
252         }
253
254         // Handle case when target is a string or something (possible in deep copy)
255         if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
256                 target = {};
257         }
258
259         // extend jQuery itself if only one argument is passed
260         if ( length === i ) {
261                 target = this;
262                 --i;
263         }
264
265         for ( ; i < length; i++ ) {
266                 // Only deal with non-null/undefined values
267                 if ( (options = arguments[ i ]) != null ) {
268                         // Extend the base object
269                         for ( name in options ) {
270                                 src = target[ name ];
271                                 copy = options[ name ];
272
273                                 // Prevent never-ending loop
274                                 if ( target === copy ) {
275                                         continue;
276                                 }
277
278                                 // Recurse if we're merging object values
279                                 if ( deep && copy && typeof copy === "object" && !copy.nodeType ) {
280                                         var clone;
281
282                                         if ( src ) {
283                                                 clone = src;
284                                         } else if ( jQuery.isArray(copy) ) {
285                                                 clone = [];
286                                         } else if ( jQuery.isObject(copy) ) {
287                                                 clone = {};
288                                         } else {
289                                                 clone = copy;
290                                         }
291
292                                         // Never move original objects, clone them
293                                         target[ name ] = jQuery.extend( deep, clone, copy );
294
295                                 // Don't bring in undefined values
296                                 } else if ( copy !== undefined ) {
297                                         target[ name ] = copy;
298                                 }
299                         }
300                 }
301         }
302
303         // Return the modified object
304         return target;
305 };
306
307 jQuery.extend({
308         noConflict: function( deep ) {
309                 window.$ = _$;
310
311                 if ( deep ) {
312                         window.jQuery = _jQuery;
313                 }
314
315                 return jQuery;
316         },
317
318         // See test/unit/core.js for details concerning isFunction.
319         // Since version 1.3, DOM methods and functions like alert
320         // aren't supported. They return false on IE (#2968).
321         isFunction: function( obj ) {
322                 return toString.call(obj) === "[object Function]";
323         },
324
325         isArray: function( obj ) {
326                 return toString.call(obj) === "[object Array]";
327         },
328
329         isObject: function( obj ) {
330                 return this.constructor.call(obj) === Object;
331         },
332
333         isEmptyObject: function( obj ) {
334                 for ( var name in obj ) {
335                         return false;
336                 }
337                 return true;
338         },
339
340         // check if an element is in a (or is an) XML document
341         isXMLDoc: function( elem ) {
342                 // documentElement is verified for cases where it doesn't yet exist
343                 // (such as loading iframes in IE - #4833)
344                 var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
345                 return documentElement ? documentElement.nodeName !== "HTML" : false;
346         },
347
348         // Evalulates a script in a global context
349         globalEval: function( data ) {
350                 if ( data && rnotwhite.test(data) ) {
351                         // Inspired by code by Andrea Giammarchi
352                         // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
353                         var head = document.getElementsByTagName("head")[0] || document.documentElement,
354                                 script = document.createElement("script");
355
356                         script.type = "text/javascript";
357
358                         if ( jQuery.support.scriptEval ) {
359                                 script.appendChild( document.createTextNode( data ) );
360                         } else {
361                                 script.text = data;
362                         }
363
364                         // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
365                         // This arises when a base node is used (#2709).
366                         head.insertBefore( script, head.firstChild );
367                         head.removeChild( script );
368                 }
369         },
370
371         nodeName: function( elem, name ) {
372                 return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
373         },
374
375         // args is for internal usage only
376         each: function( object, callback, args ) {
377                 var name, i = 0,
378                         length = object.length,
379                         isObj = length === undefined || jQuery.isFunction(object);
380
381                 if ( args ) {
382                         if ( isObj ) {
383                                 for ( name in object ) {
384                                         if ( callback.apply( object[ name ], args ) === false ) {
385                                                 break;
386                                         }
387                                 }
388                         } else {
389                                 for ( ; i < length; ) {
390                                         if ( callback.apply( object[ i++ ], args ) === false ) {
391                                                 break;
392                                         }
393                                 }
394                         }
395
396                 // A special, fast, case for the most common use of each
397                 } else {
398                         if ( isObj ) {
399                                 for ( name in object ) {
400                                         if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
401                                                 break;
402                                         }
403                                 }
404                         } else {
405                                 for ( var value = object[0];
406                                         i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
407                         }
408                 }
409
410                 return object;
411         },
412
413         trim: function( text ) {
414                 return (text || "").replace( rtrim, "" );
415         },
416
417         makeArray: function( array ) {
418                 var ret = [], i;
419
420                 if ( array != null ) {
421                         i = array.length;
422
423                         // The window, strings (and functions) also have 'length'
424                         if ( i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval ) {
425                                 ret[0] = array;
426                         } else {
427                                 while ( i ) {
428                                         ret[--i] = array[i];
429                                 }
430                         }
431                 }
432
433                 return ret;
434         },
435
436         inArray: function( elem, array ) {
437                 for ( var i = 0, length = array.length; i < length; i++ ) {
438                         if ( array[ i ] === elem ) {
439                                 return i;
440                         }
441                 }
442
443                 return -1;
444         },
445
446         merge: function( first, second ) {
447                 // We have to loop this way because IE & Opera overwrite the length
448                 // expando of getElementsByTagName
449                 var i = 0, elem, pos = first.length;
450
451                 // Also, we need to make sure that the correct elements are being returned
452                 // (IE returns comment nodes in a '*' query)
453                 if ( !jQuery.support.getAll ) {
454                         while ( (elem = second[ i++ ]) != null ) {
455                                 if ( elem.nodeType !== 8 ) {
456                                         first[ pos++ ] = elem;
457                                 }
458                         }
459
460                 } else {
461                         while ( (elem = second[ i++ ]) != null ) {
462                                 first[ pos++ ] = elem;
463                         }
464                 }
465
466                 return first;
467         },
468
469         unique: function( array ) {
470                 var ret = [], done = {}, id;
471
472                 try {
473                         for ( var i = 0, length = array.length; i < length; i++ ) {
474                                 id = jQuery.data( array[ i ] );
475
476                                 if ( !done[ id ] ) {
477                                         done[ id ] = true;
478                                         ret.push( array[ i ] );
479                                 }
480                         }
481                 } catch( e ) {
482                         ret = array;
483                 }
484
485                 return ret;
486         },
487
488         grep: function( elems, callback, inv ) {
489                 var ret = [];
490
491                 // Go through the array, only saving the items
492                 // that pass the validator function
493                 for ( var i = 0, length = elems.length; i < length; i++ ) {
494                         if ( !inv !== !callback( elems[ i ], i ) ) {
495                                 ret.push( elems[ i ] );
496                         }
497                 }
498
499                 return ret;
500         },
501
502         map: function( elems, callback ) {
503                 var ret = [], value;
504
505                 // Go through the array, translating each of the items to their
506                 // new value (or values).
507                 for ( var i = 0, length = elems.length; i < length; i++ ) {
508                         value = callback( elems[ i ], i );
509
510                         if ( value != null ) {
511                                 ret[ ret.length ] = value;
512                         }
513                 }
514
515                 return ret.concat.apply( [], ret );
516         },
517
518         // Use of jQuery.browser is deprecated.
519         // It's included for backwards compatibility and plugins,
520         // although they should work to migrate away.
521         browser: {
522                 version: (/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/.exec(userAgent) || [0,'0'])[1],
523                 safari: /webkit/.test( userAgent ),
524                 opera: /opera/.test( userAgent ),
525                 msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
526                 mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
527         }
528 });
529
530 if ( indexOf ) {
531         jQuery.inArray = function( elem, array ) {
532                 return indexOf.call( array, elem );
533         };
534 }
535
536 // All jQuery objects should point back to these
537 rootjQuery = jQuery(document);
538
539 function evalScript( i, elem ) {
540         if ( elem.src ) {
541                 jQuery.ajax({
542                         url: elem.src,
543                         async: false,
544                         dataType: "script"
545                 });
546         } else {
547                 jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
548         }
549
550         if ( elem.parentNode ) {
551                 elem.parentNode.removeChild( elem );
552         }
553 }
554
555 function now() {
556         return (new Date).getTime();
557 }