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