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