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