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