Make sure that dynamically-created elements don't have a parent. Fixes #5638.
[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 new jQuery.fn.init( selector, context );
5         },
6
7         // Map over jQuery in case of overwrite
8         _jQuery = window.jQuery,
9
10         // Map over the $ in case of overwrite
11         _$ = window.$,
12
13         // Use the correct document accordingly with window argument (sandbox)
14         document = window.document,
15
16         // A central reference to the root jQuery(document)
17         rootjQuery,
18
19         // A simple way to check for HTML strings or ID strings
20         // (both of which we optimize for)
21         quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,
22
23         // Is it a simple selector
24         isSimple = /^.[^:#\[\.,]*$/,
25
26         // Check if a string has a non-whitespace character in it
27         rnotwhite = /\S/,
28
29         // Used for trimming whitespace
30         rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g,
31
32         // Match a standalone tag
33         rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
34
35         // Keep a UserAgent string for use with jQuery.browser
36         userAgent = navigator.userAgent.toLowerCase(),
37         
38         // Has the ready events already been bound?
39         readyBound = false,
40         
41         // The functions to execute on DOM ready
42         readyList = [],
43
44         // Save a reference to some core methods
45         toString = Object.prototype.toString,
46         hasOwnProperty = Object.prototype.hasOwnProperty,
47         push = Array.prototype.push,
48         slice = Array.prototype.slice,
49         indexOf = Array.prototype.indexOf;
50
51 jQuery.fn = jQuery.prototype = {
52         init: function( selector, context ) {
53                 var match, elem, ret, doc, parent;
54
55                 // Handle $(""), $(null), or $(undefined)
56                 if ( !selector ) {
57                         return this;
58                 }
59
60                 // Handle $(DOMElement)
61                 if ( selector.nodeType ) {
62                         this.context = this[0] = selector;
63                         this.length = 1;
64                         return this;
65                 }
66
67                 // Handle HTML strings
68                 if ( typeof selector === "string" ) {
69                         // Are we dealing with HTML string or an ID?
70                         match = quickExpr.exec( selector );
71
72                         // Verify a match, and that no context was specified for #id
73                         if ( match && (match[1] || !context) ) {
74
75                                 // HANDLE: $(html) -> $(array)
76                                 if ( match[1] ) {
77                                         doc = (context ? context.ownerDocument || context : document);
78
79                                         // If a single string is passed in and it's a single tag
80                                         // just do a createElement and skip the rest
81                                         ret = rsingleTag.exec( selector );
82
83                                         if ( ret ) {
84                                                 selector = [ doc.createElement( ret[1] ) ];
85
86                                         } else {
87                                                 ret = buildFragment( [ match[1] ], [ doc ] );
88                                                 parent = ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment;
89                                                 selector = [];
90
91                                                 while ( parent.firstChild ) {
92                                                         selector.push( parent.removeChild( parent.firstChild ) );
93                                                 }
94                                         }
95
96                                 // HANDLE: $("#id")
97                                 } else {
98                                         elem = document.getElementById( match[2] );
99
100                                         if ( elem ) {
101                                                 // Handle the case where IE and Opera return items
102                                                 // by name instead of ID
103                                                 if ( elem.id !== match[2] ) {
104                                                         return rootjQuery.find( selector );
105                                                 }
106
107                                                 // Otherwise, we inject the element directly into the jQuery object
108                                                 this.length = 1;
109                                                 this[0] = elem;
110                                         }
111
112                                         this.context = document;
113                                         this.selector = selector;
114                                         return this;
115                                 }
116
117                         // HANDLE: $("TAG")
118                         } else if ( !context && /^\w+$/.test( selector ) ) {
119                                 this.selector = selector;
120                                 this.context = document;
121                                 selector = document.getElementsByTagName( selector );
122
123                         // HANDLE: $(expr, $(...))
124                         } else if ( !context || context.jquery ) {
125                                 return (context || rootjQuery).find( selector );
126
127                         // HANDLE: $(expr, context)
128                         // (which is just equivalent to: $(context).find(expr)
129                         } else {
130                                 return jQuery( context ).find( selector );
131                         }
132
133                 // HANDLE: $(function)
134                 // Shortcut for document ready
135                 } else if ( jQuery.isFunction( selector ) ) {
136                         return rootjQuery.ready( selector );
137                 }
138
139                 if (selector.selector !== undefined) {
140                         this.selector = selector.selector;
141                         this.context = selector.context;
142                 }
143
144                 return jQuery.isArray( selector ) ?
145                         this.setArray( selector ) :
146                         jQuery.makeArray( selector, this );
147         },
148
149         // Start with an empty selector
150         selector: "",
151
152         // The current version of jQuery being used
153         jquery: "@VERSION",
154
155         // The default length of a jQuery object is 0
156         length: 0,
157
158         // The number of elements contained in the matched element set
159         size: function() {
160                 return this.length;
161         },
162
163         toArray: function(){
164                 return slice.call( this, 0 );
165         },
166
167         // Get the Nth element in the matched element set OR
168         // Get the whole matched element set as a clean array
169         get: function( num ) {
170                 return num == null ?
171
172                         // Return a 'clean' array
173                         this.toArray() :
174
175                         // Return just the object
176                         ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
177         },
178
179         // Take an array of elements and push it onto the stack
180         // (returning the new matched element set)
181         pushStack: function( elems, name, selector ) {
182                 // Build a new jQuery matched element set
183                 var ret = jQuery( elems || null );
184
185                 // Add the old object onto the stack (as a reference)
186                 ret.prevObject = this;
187
188                 ret.context = this.context;
189
190                 if ( name === "find" ) {
191                         ret.selector = this.selector + (this.selector ? " " : "") + selector;
192                 } else if ( name ) {
193                         ret.selector = this.selector + "." + name + "(" + selector + ")";
194                 }
195
196                 // Return the newly-formed element set
197                 return ret;
198         },
199
200         // Force the current matched set of elements to become
201         // the specified array of elements (destroying the stack in the process)
202         // You should use pushStack() in order to do this, but maintain the stack
203         setArray: function( elems ) {
204                 // Resetting the length to 0, then using the native Array push
205                 // is a super-fast way to populate an object with array-like properties
206                 this.length = 0;
207                 push.apply( this, elems );
208
209                 return this;
210         },
211
212         // Execute a callback for every element in the matched set.
213         // (You can seed the arguments with an array of args, but this is
214         // only used internally.)
215         each: function( callback, args ) {
216                 return jQuery.each( this, callback, args );
217         },
218         
219         ready: function( fn ) {
220                 // Attach the listeners
221                 jQuery.bindReady();
222
223                 // If the DOM is already ready
224                 if ( jQuery.isReady && !readyList ) {
225                         // Execute the function immediately
226                         fn.call( document, jQuery );
227
228                 // Otherwise, remember the function for later
229                 } else {
230                         // Add the function to the wait list
231                         readyList.push( fn );
232                 }
233
234                 return this;
235         },
236         
237         eq: function( i ) {
238                 return i === -1 ?
239                         this.slice( i ) :
240                         this.slice( i, +i + 1 );
241         },
242
243         first: function() {
244                 return this.eq( 0 );
245         },
246
247         last: function() {
248                 return this.eq( -1 );
249         },
250
251         slice: function() {
252                 return this.pushStack( slice.apply( this, arguments ),
253                         "slice", slice.call(arguments).join(",") );
254         },
255
256         map: function( callback ) {
257                 return this.pushStack( jQuery.map(this, function(elem, i){
258                         return callback.call( elem, i, elem );
259                 }));
260         },
261         
262         end: function() {
263                 return this.prevObject || jQuery(null);
264         },
265
266         // For internal use only.
267         // Behaves like an Array's method, not like a jQuery method.
268         push: push,
269         sort: [].sort,
270         splice: [].splice
271 };
272
273 // Give the init function the jQuery prototype for later instantiation
274 jQuery.fn.init.prototype = jQuery.fn;
275
276 jQuery.extend = jQuery.fn.extend = function() {
277         // copy reference to target object
278         var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;
279
280         // Handle a deep copy situation
281         if ( typeof target === "boolean" ) {
282                 deep = target;
283                 target = arguments[1] || {};
284                 // skip the boolean and the target
285                 i = 2;
286         }
287
288         // Handle case when target is a string or something (possible in deep copy)
289         if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
290                 target = {};
291         }
292
293         // extend jQuery itself if only one argument is passed
294         if ( length === i ) {
295                 target = this;
296                 --i;
297         }
298
299         for ( ; i < length; i++ ) {
300                 // Only deal with non-null/undefined values
301                 if ( (options = arguments[ i ]) != null ) {
302                         // Extend the base object
303                         for ( name in options ) {
304                                 src = target[ name ];
305                                 copy = options[ name ];
306
307                                 // Prevent never-ending loop
308                                 if ( target === copy ) {
309                                         continue;
310                                 }
311
312                                 // Recurse if we're merging object literal values
313                                 if ( deep && copy && jQuery.isPlainObject(copy) ) {
314                                         // Don't extend not object literals
315                                         var clone = src && jQuery.isPlainObject(src) ? src : {};
316
317                                         // Never move original objects, clone them
318                                         target[ name ] = jQuery.extend( deep, clone, copy );
319
320                                 // Don't bring in undefined values
321                                 } else if ( copy !== undefined ) {
322                                         target[ name ] = copy;
323                                 }
324                         }
325                 }
326         }
327
328         // Return the modified object
329         return target;
330 };
331
332 jQuery.extend({
333         noConflict: function( deep ) {
334                 window.$ = _$;
335
336                 if ( deep ) {
337                         window.jQuery = _jQuery;
338                 }
339
340                 return jQuery;
341         },
342         
343         // Is the DOM ready to be used? Set to true once it occurs.
344         isReady: false,
345         
346         // Handle when the DOM is ready
347         ready: function() {
348                 // Make sure that the DOM is not already loaded
349                 if ( !jQuery.isReady ) {
350                         if ( !document.body ) {
351                                 return setTimeout( jQuery.ready, 13 );
352                         }
353
354                         // Remember that the DOM is ready
355                         jQuery.isReady = true;
356
357                         // If there are functions bound, to execute
358                         if ( readyList ) {
359                                 // Execute all of them
360                                 var fn, i = 0;
361                                 while ( (fn = readyList[ i++ ]) ) {
362                                         fn.call( document, jQuery );
363                                 }
364
365                                 // Reset the list of functions
366                                 readyList = null;
367                         }
368
369                         // Trigger any bound ready events
370                         if ( jQuery.fn.triggerHandler ) {
371                                 jQuery( document ).triggerHandler( "ready" );
372                         }
373                 }
374         },
375         
376         bindReady: function() {
377                 if ( readyBound ) { return; }
378                 readyBound = true;
379
380                 // Catch cases where $(document).ready() is called after the
381                 // browser event has already occurred.
382                 if ( document.readyState === "complete" ) {
383                         return jQuery.ready();
384                 }
385
386                 // Mozilla, Opera and webkit nightlies currently support this event
387                 if ( document.addEventListener ) {
388                         // Use the handy event callback
389                         document.addEventListener( "DOMContentLoaded", function DOMContentLoaded() {
390                                 document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
391                                 jQuery.ready();
392                         }, false );
393                         
394                         // A fallback to window.onload, that will always work
395                         window.addEventListener( "load", jQuery.ready, false );
396
397                 // If IE event model is used
398                 } else if ( document.attachEvent ) {
399                         // ensure firing before onload,
400                         // maybe late but safe also for iframes
401                         document.attachEvent("onreadystatechange", function onreadystatechange() {
402                                 // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
403                                 if ( document.readyState === "complete" ) {
404                                         document.detachEvent( "onreadystatechange", onreadystatechange );
405                                         jQuery.ready();
406                                 }
407                         });
408                         
409                         // A fallback to window.onload, that will always work
410                         window.attachEvent( "onload", jQuery.ready );
411
412                         // If IE and not a frame
413                         // continually check to see if the document is ready
414                         var toplevel = false;
415
416                         try {
417                                 toplevel = window.frameElement == null;
418                         } catch(e){}
419
420                         if ( document.documentElement.doScroll && toplevel ) {
421                                 doScrollCheck();
422
423                                 function doScrollCheck() {
424                                         if ( jQuery.isReady ) {
425                                                 return;
426                                         }
427
428                                         try {
429                                                 // If IE is used, use the trick by Diego Perini
430                                                 // http://javascript.nwbox.com/IEContentLoaded/
431                                                 document.documentElement.doScroll("left");
432                                         } catch( error ) {
433                                                 setTimeout( doScrollCheck, 1 );
434                                                 return;
435                                         }
436
437                                         // and execute any waiting functions
438                                         jQuery.ready();
439                                 }
440                         }
441                 }
442         },
443
444         // See test/unit/core.js for details concerning isFunction.
445         // Since version 1.3, DOM methods and functions like alert
446         // aren't supported. They return false on IE (#2968).
447         isFunction: function( obj ) {
448                 return toString.call(obj) === "[object Function]";
449         },
450
451         isArray: function( obj ) {
452                 return toString.call(obj) === "[object Array]";
453         },
454
455         isPlainObject: function( obj ) {
456                 if ( toString.call(obj) !== "[object Object]" || typeof obj.nodeType === "number" ) {
457                         return false;
458                 }
459                 
460                 // not own constructor property must be Object
461                 if ( obj.constructor
462                         && !hasOwnProperty.call(obj, "constructor")
463                         && !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) {
464                         return false;
465                 }
466                 
467                 //own properties are iterated firstly,
468                 //so to speed up, we can test last one if it is own or not
469         
470                 var key;
471                 for ( key in obj ) {}
472                 
473                 return key === undefined || hasOwnProperty.call( obj, key );
474         },
475
476         isEmptyObject: function( obj ) {
477                 for ( var name in obj ) {
478                         return false;
479                 }
480                 return true;
481         },
482
483         // Evalulates a script in a global context
484         globalEval: function( data ) {
485                 if ( data && rnotwhite.test(data) ) {
486                         // Inspired by code by Andrea Giammarchi
487                         // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
488                         var head = document.getElementsByTagName("head")[0] || document.documentElement,
489                                 script = document.createElement("script");
490
491                         script.type = "text/javascript";
492
493                         if ( jQuery.support.scriptEval ) {
494                                 script.appendChild( document.createTextNode( data ) );
495                         } else {
496                                 script.text = data;
497                         }
498
499                         // Use insertBefore instead of appendChild to circumvent an IE6 bug.
500                         // This arises when a base node is used (#2709).
501                         head.insertBefore( script, head.firstChild );
502                         head.removeChild( script );
503                 }
504         },
505
506         nodeName: function( elem, name ) {
507                 return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
508         },
509
510         // args is for internal usage only
511         each: function( object, callback, args ) {
512                 var name, i = 0,
513                         length = object.length,
514                         isObj = length === undefined || jQuery.isFunction(object);
515
516                 if ( args ) {
517                         if ( isObj ) {
518                                 for ( name in object ) {
519                                         if ( callback.apply( object[ name ], args ) === false ) {
520                                                 break;
521                                         }
522                                 }
523                         } else {
524                                 for ( ; i < length; ) {
525                                         if ( callback.apply( object[ i++ ], args ) === false ) {
526                                                 break;
527                                         }
528                                 }
529                         }
530
531                 // A special, fast, case for the most common use of each
532                 } else {
533                         if ( isObj ) {
534                                 for ( name in object ) {
535                                         if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
536                                                 break;
537                                         }
538                                 }
539                         } else {
540                                 for ( var value = object[0];
541                                         i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
542                         }
543                 }
544
545                 return object;
546         },
547
548         trim: function( text ) {
549                 return (text || "").replace( rtrim, "" );
550         },
551
552         // results is for internal usage only
553         makeArray: function( array, results ) {
554                 var ret = results || [];
555
556                 if ( array != null ) {
557                         // The window, strings (and functions) also have 'length'
558                         // The extra typeof function check is to prevent crashes
559                         // in Safari 2 (See: #3039)
560                         if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) {
561                                 push.call( ret, array );
562                         } else {
563                                 jQuery.merge( ret, array );
564                         }
565                 }
566
567                 return ret;
568         },
569
570         inArray: function( elem, array ) {
571                 if ( array.indexOf ) {
572                         return array.indexOf( elem );
573                 }
574
575                 for ( var i = 0, length = array.length; i < length; i++ ) {
576                         if ( array[ i ] === elem ) {
577                                 return i;
578                         }
579                 }
580
581                 return -1;
582         },
583
584         merge: function( first, second ) {
585                 var i = first.length, j = 0;
586
587                 if ( typeof second.length === "number" ) {
588                         for ( var l = second.length; j < l; j++ ) {
589                                 first[ i++ ] = second[ j ];
590                         }
591                 } else {
592                         while ( second[j] !== undefined ) {
593                                 first[ i++ ] = second[ j++ ];
594                         }
595                 }
596
597                 first.length = i;
598
599                 return first;
600         },
601
602         grep: function( elems, callback, inv ) {
603                 var ret = [];
604
605                 // Go through the array, only saving the items
606                 // that pass the validator function
607                 for ( var i = 0, length = elems.length; i < length; i++ ) {
608                         if ( !inv !== !callback( elems[ i ], i ) ) {
609                                 ret.push( elems[ i ] );
610                         }
611                 }
612
613                 return ret;
614         },
615
616         // arg is for internal usage only
617         map: function( elems, callback, arg ) {
618                 var ret = [], value;
619
620                 // Go through the array, translating each of the items to their
621                 // new value (or values).
622                 for ( var i = 0, length = elems.length; i < length; i++ ) {
623                         value = callback( elems[ i ], i, arg );
624
625                         if ( value != null ) {
626                                 ret[ ret.length ] = value;
627                         }
628                 }
629
630                 return ret.concat.apply( [], ret );
631         },
632
633         // Use of jQuery.browser is frowned upon.
634         // More details: http://docs.jquery.com/Utilities/jQuery.browser
635         browser: {
636                 version: (/.*?(?:firefox|safari|opera|msie)[\/ ]([\d.]+)/.exec(userAgent) || [0,'0'])[1],
637                 safari: /safari/.test( userAgent ),
638                 opera: /opera/.test( userAgent ),
639                 msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
640                 firefox: /firefox/.test( userAgent )
641         }
642 });
643
644 // Deprecated
645 jQuery.browser.mozilla = /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent );
646
647 if ( indexOf ) {
648         jQuery.inArray = function( elem, array ) {
649                 return indexOf.call( array, elem );
650         };
651 }
652
653 // All jQuery objects should point back to these
654 rootjQuery = jQuery(document);
655
656 function evalScript( i, elem ) {
657         if ( elem.src ) {
658                 jQuery.ajax({
659                         url: elem.src,
660                         async: false,
661                         dataType: "script"
662                 });
663         } else {
664                 jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
665         }
666
667         if ( elem.parentNode ) {
668                 elem.parentNode.removeChild( elem );
669         }
670 }
671
672 // Mutifunctional method to get and set values to a collection
673 // The value/s can be optionally by executed if its a function
674 function access( elems, key, value, exec, fn ) {
675         var length = elems.length;
676         
677         // Setting many attributes
678         if ( typeof key === "object" ) {
679                 for ( var k in key ) {
680                         access( elems, k, key[k], exec, fn );
681                 }
682                 return elems;
683         }
684         
685         // Setting one attribute
686         if ( value !== undefined ) {
687                 // Optionally, function values get executed if exec is true
688                 exec = exec && jQuery.isFunction(value);
689                 
690                 for ( var i = 0; i < length; i++ ) {
691                         fn( elems[i], key, exec ? value.call( elems[i], i ) : value );
692                 }
693                 
694                 return elems;
695         }
696         
697         // Getting an attribute
698         return length ? fn( elems[0], key ) : null;
699 }
700
701 function now() {
702         return (new Date).getTime();
703 }