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