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