2.0: Reduced parseXML
[jquery.git] / src / core.js
blob55ed4317f4b8cbf5353cfbbfbe6f1f602e6fccba
1 var
2         // A central reference to the root jQuery(document)
3         rootjQuery,
5         // The deferred used on DOM ready
6         readyList,
8         // Use the correct document accordingly with window argument (sandbox)
9         document = window.document,
10         location = window.location,
12         // Map over jQuery in case of overwrite
13         _jQuery = window.jQuery,
15         // Map over the $ in case of overwrite
16         _$ = window.$,
18         // [[Class]] -> type pairs
19         class2type = {},
21         // List of deleted data cache ids, so we can reuse them
22         core_deletedIds = [],
24         core_version = "@VERSION",
26         // Save a reference to some core methods
27         core_concat = core_deletedIds.concat,
28         core_push = core_deletedIds.push,
29         core_slice = core_deletedIds.slice,
30         core_indexOf = core_deletedIds.indexOf,
31         core_toString = class2type.toString,
32         core_hasOwn = class2type.hasOwnProperty,
33         core_trim = core_version.trim,
35         // Define a local copy of jQuery
36         jQuery = function( selector, context ) {
37                 // The jQuery object is actually just the init constructor 'enhanced'
38                 return new jQuery.fn.init( selector, context, rootjQuery );
39         },
41         // Used for matching numbers
42         core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
44         // Used for splitting on whitespace
45         core_rnotwhite = /\S+/g,
47         // A simple way to check for HTML strings
48         // Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
49         // Strict HTML recognition (#11290: must start with <)
50         rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,
52         // Match a standalone tag
53         rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
55         // Matches dashed string for camelizing
56         rmsPrefix = /^-ms-/,
57         rdashAlpha = /-([\da-z])/gi,
59         // Used by jQuery.camelCase as callback to replace()
60         fcamelCase = function( all, letter ) {
61                 return letter.toUpperCase();
62         },
64         // The ready event handler and self cleanup method
65         DOMContentLoaded = function() {
66                 document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
67                 jQuery.ready();
68         };
70 jQuery.fn = jQuery.prototype = {
71         // The current version of jQuery being used
72         jquery: core_version,
74         constructor: jQuery,
75         init: function( selector, context, rootjQuery ) {
76                 var match, elem;
78                 // HANDLE: $(""), $(null), $(undefined), $(false)
79                 if ( !selector ) {
80                         return this;
81                 }
83                 // Handle HTML strings
84                 if ( typeof selector === "string" ) {
85                         if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
86                                 // Assume that strings that start and end with <> are HTML and skip the regex check
87                                 match = [ null, selector, null ];
89                         } else {
90                                 match = rquickExpr.exec( selector );
91                         }
93                         // Match html or make sure no context is specified for #id
94                         if ( match && (match[1] || !context) ) {
96                                 // HANDLE: $(html) -> $(array)
97                                 if ( match[1] ) {
98                                         context = context instanceof jQuery ? context[0] : context;
100                                         // scripts is true for back-compat
101                                         jQuery.merge( this, jQuery.parseHTML(
102                                                 match[1],
103                                                 context && context.nodeType ? context.ownerDocument || context : document,
104                                                 true
105                                         ) );
107                                         // HANDLE: $(html, props)
108                                         if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
109                                                 for ( match in context ) {
110                                                         // Properties of context are called as methods if possible
111                                                         if ( jQuery.isFunction( this[ match ] ) ) {
112                                                                 this[ match ]( context[ match ] );
114                                                         // ...and otherwise set as attributes
115                                                         } else {
116                                                                 this.attr( match, context[ match ] );
117                                                         }
118                                                 }
119                                         }
121                                         return this;
123                                 // HANDLE: $(#id)
124                                 } else {
125                                         elem = document.getElementById( match[2] );
127                                         // Check parentNode to catch when Blackberry 4.6 returns
128                                         // nodes that are no longer in the document #6963
129                                         if ( elem && elem.parentNode ) {
130                                                 // Handle the case where IE and Opera return items
131                                                 // by name instead of ID
132                                                 if ( elem.id !== match[2] ) {
133                                                         return rootjQuery.find( selector );
134                                                 }
136                                                 // Otherwise, we inject the element directly into the jQuery object
137                                                 this.length = 1;
138                                                 this[0] = elem;
139                                         }
141                                         this.context = document;
142                                         this.selector = selector;
143                                         return this;
144                                 }
146                         // HANDLE: $(expr, $(...))
147                         } else if ( !context || context.jquery ) {
148                                 return ( context || rootjQuery ).find( selector );
150                         // HANDLE: $(expr, context)
151                         // (which is just equivalent to: $(context).find(expr)
152                         } else {
153                                 return this.constructor( context ).find( selector );
154                         }
156                 // HANDLE: $(DOMElement)
157                 } else if ( selector.nodeType ) {
158                         this.context = this[0] = selector;
159                         this.length = 1;
160                         return this;
162                 // HANDLE: $(function)
163                 // Shortcut for document ready
164                 } else if ( jQuery.isFunction( selector ) ) {
165                         return rootjQuery.ready( selector );
166                 }
168                 if ( selector.selector !== undefined ) {
169                         this.selector = selector.selector;
170                         this.context = selector.context;
171                 }
173                 return jQuery.makeArray( selector, this );
174         },
176         // Start with an empty selector
177         selector: "",
179         // The default length of a jQuery object is 0
180         length: 0,
182         // The number of elements contained in the matched element set
183         size: function() {
184                 return this.length;
185         },
187         toArray: function() {
188                 return core_slice.call( this );
189         },
191         // Get the Nth element in the matched element set OR
192         // Get the whole matched element set as a clean array
193         get: function( num ) {
194                 return num == null ?
196                         // Return a 'clean' array
197                         this.toArray() :
199                         // Return just the object
200                         ( num < 0 ? this[ this.length + num ] : this[ num ] );
201         },
203         // Take an array of elements and push it onto the stack
204         // (returning the new matched element set)
205         pushStack: function( elems ) {
207                 // Build a new jQuery matched element set
208                 var ret = jQuery.merge( this.constructor(), elems );
210                 // Add the old object onto the stack (as a reference)
211                 ret.prevObject = this;
212                 ret.context = this.context;
214                 // Return the newly-formed element set
215                 return ret;
216         },
218         // Execute a callback for every element in the matched set.
219         // (You can seed the arguments with an array of args, but this is
220         // only used internally.)
221         each: function( callback, args ) {
222                 return jQuery.each( this, callback, args );
223         },
225         ready: function( fn ) {
226                 // Add the callback
227                 jQuery.ready.promise().done( fn );
229                 return this;
230         },
232         slice: function() {
233                 return this.pushStack( core_slice.apply( this, arguments ) );
234         },
236         first: function() {
237                 return this.eq( 0 );
238         },
240         last: function() {
241                 return this.eq( -1 );
242         },
244         eq: function( i ) {
245                 var len = this.length,
246                         j = +i + ( i < 0 ? len : 0 );
247                 return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
248         },
250         map: function( callback ) {
251                 return this.pushStack( jQuery.map(this, function( elem, i ) {
252                         return callback.call( elem, i, elem );
253                 }));
254         },
256         end: function() {
257                 return this.prevObject || this.constructor(null);
258         },
260         // For internal use only.
261         // Behaves like an Array's method, not like a jQuery method.
262         push: core_push,
263         sort: [].sort,
264         splice: [].splice
267 // Give the init function the jQuery prototype for later instantiation
268 jQuery.fn.init.prototype = jQuery.fn;
270 jQuery.extend = jQuery.fn.extend = function() {
271         var options, name, src, copy, copyIsArray, clone,
272                 target = arguments[0] || {},
273                 i = 1,
274                 length = arguments.length,
275                 deep = false;
277         // Handle a deep copy situation
278         if ( typeof target === "boolean" ) {
279                 deep = target;
280                 target = arguments[1] || {};
281                 // skip the boolean and the target
282                 i = 2;
283         }
285         // Handle case when target is a string or something (possible in deep copy)
286         if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
287                 target = {};
288         }
290         // extend jQuery itself if only one argument is passed
291         if ( length === i ) {
292                 target = this;
293                 --i;
294         }
296         for ( ; i < length; i++ ) {
297                 // Only deal with non-null/undefined values
298                 if ( (options = arguments[ i ]) != null ) {
299                         // Extend the base object
300                         for ( name in options ) {
301                                 src = target[ name ];
302                                 copy = options[ name ];
304                                 // Prevent never-ending loop
305                                 if ( target === copy ) {
306                                         continue;
307                                 }
309                                 // Recurse if we're merging plain objects or arrays
310                                 if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
311                                         if ( copyIsArray ) {
312                                                 copyIsArray = false;
313                                                 clone = src && jQuery.isArray(src) ? src : [];
315                                         } else {
316                                                 clone = src && jQuery.isPlainObject(src) ? src : {};
317                                         }
319                                         // Never move original objects, clone them
320                                         target[ name ] = jQuery.extend( deep, clone, copy );
322                                 // Don't bring in undefined values
323                                 } else if ( copy !== undefined ) {
324                                         target[ name ] = copy;
325                                 }
326                         }
327                 }
328         }
330         // Return the modified object
331         return target;
334 jQuery.extend({
335         noConflict: function( deep ) {
336                 if ( window.$ === jQuery ) {
337                         window.$ = _$;
338                 }
340                 if ( deep && window.jQuery === jQuery ) {
341                         window.jQuery = _jQuery;
342                 }
344                 return jQuery;
345         },
347         // Is the DOM ready to be used? Set to true once it occurs.
348         isReady: false,
350         // A counter to track how many items to wait for before
351         // the ready event fires. See #6781
352         readyWait: 1,
354         // Hold (or release) the ready event
355         holdReady: function( hold ) {
356                 if ( hold ) {
357                         jQuery.readyWait++;
358                 } else {
359                         jQuery.ready( true );
360                 }
361         },
363         // Handle when the DOM is ready
364         ready: function( wait ) {
366                 // Abort if there are pending holds or we're already ready
367                 if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
368                         return;
369                 }
371                 // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
372                 if ( !document.body ) {
373                         return setTimeout( jQuery.ready );
374                 }
376                 // Remember that the DOM is ready
377                 jQuery.isReady = true;
379                 // If a normal DOM Ready event fired, decrement, and wait if need be
380                 if ( wait !== true && --jQuery.readyWait > 0 ) {
381                         return;
382                 }
384                 // If there are functions bound, to execute
385                 readyList.resolveWith( document, [ jQuery ] );
387                 // Trigger any bound ready events
388                 if ( jQuery.fn.trigger ) {
389                         jQuery( document ).trigger("ready").off("ready");
390                 }
391         },
393         // See test/unit/core.js for details concerning isFunction.
394         // Since version 1.3, DOM methods and functions like alert
395         // aren't supported. They return false on IE (#2968).
396         isFunction: function( obj ) {
397                 return jQuery.type(obj) === "function";
398         },
400         isArray: Array.isArray,
402         isWindow: function( obj ) {
403                 return obj != null && obj == obj.window;
404         },
406         isNumeric: function( obj ) {
407                 return !isNaN( parseFloat(obj) ) && isFinite( obj );
408         },
410         type: function( obj ) {
411                 if ( obj == null ) {
412                         return String( obj );
413                 }
414                 return typeof obj === "object" || typeof obj === "function" ?
415                         class2type[ core_toString.call(obj) ] || "object" :
416                         typeof obj;
417         },
419         isPlainObject: function( obj ) {
420                 // Not plain objects: params that are not [[Class]] "[object Object]", DOM nodes, window
421                 if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
422                         return false;
423                 }
425                 // Firefox 17+ will throw on host objects. ie window.location
426                 try {
427                         if ( obj.constructor &&
428                                         !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
429                                 return false;
430                         }
431                 } catch ( e ) {
432                         return false;
433                 }
435                 return obj === Object( obj );
436         },
438         isEmptyObject: function( obj ) {
439                 var name;
440                 for ( name in obj ) {
441                         return false;
442                 }
443                 return true;
444         },
446         error: function( msg ) {
447                 throw new Error( msg );
448         },
450         // data: string of html
451         // context (optional): If specified, the fragment will be created in this context, defaults to document
452         // keepScripts (optional): If true, will include scripts passed in the html string
453         parseHTML: function( data, context, keepScripts ) {
454                 if ( !data || typeof data !== "string" ) {
455                         return null;
456                 }
457                 if ( typeof context === "boolean" ) {
458                         keepScripts = context;
459                         context = false;
460                 }
461                 context = context || document;
463                 var parsed = rsingleTag.exec( data ),
464                         scripts = !keepScripts && [];
466                 // Single tag
467                 if ( parsed ) {
468                         return [ context.createElement( parsed[1] ) ];
469                 }
471                 parsed = context.createDocumentFragment();
472                 jQuery.clean( [ data ], context, parsed, scripts );
473                 if ( scripts ) {
474                         jQuery( scripts ).remove();
475                 }
476                 return jQuery.merge( [], parsed.childNodes );
477         },
479         parseJSON: function( data ) {
480                 return window.JSON.parse( data );
481         },
483         // Cross-browser xml parsing
484         parseXML: function( data ) {
485                 var xml, tmp;
486                 if ( !data || typeof data !== "string" ) {
487                         return null;
488                 }
490                 // IE9 will throw on ill-formed XML
491                 try {
492                         tmp = new DOMParser();
493                         xml = tmp.parseFromString( data , "text/xml" );
494                 } catch ( e ) {
495                         xml = undefined;
496                 }
498                 if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
499                         jQuery.error( "Invalid XML: " + data );
500                 }
501                 return xml;
502         },
504         noop: function() {},
506         // Evaluates a script in a global context
507         // Workarounds based on findings by Jim Driscoll
508         // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
509         globalEval: function( data ) {
510                 if ( data && jQuery.trim( data ) ) {
511                         // We use execScript on Internet Explorer
512                         // We use an anonymous function so that context is window
513                         // rather than jQuery in Firefox
514                         ( window.execScript || function( data ) {
515                                 window[ "eval" ].call( window, data );
516                         } )( data );
517                 }
518         },
520         // Convert dashed to camelCase; used by the css and data modules
521         // Microsoft forgot to hump their vendor prefix (#9572)
522         camelCase: function( string ) {
523                 return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
524         },
526         nodeName: function( elem, name ) {
527                 return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
528         },
530         // args is for internal usage only
531         each: function( obj, callback, args ) {
532                 var value,
533                         i = 0,
534                         length = obj.length,
535                         isArray = isArraylike( obj );
537                 if ( args ) {
538                         if ( isArray ) {
539                                 for ( ; i < length; i++ ) {
540                                         value = callback.apply( obj[ i ], args );
542                                         if ( value === false ) {
543                                                 break;
544                                         }
545                                 }
546                         } else {
547                                 for ( i in obj ) {
548                                         value = callback.apply( obj[ i ], args );
550                                         if ( value === false ) {
551                                                 break;
552                                         }
553                                 }
554                         }
556                 // A special, fast, case for the most common use of each
557                 } else {
558                         if ( isArray ) {
559                                 for ( ; i < length; i++ ) {
560                                         value = callback.call( obj[ i ], i, obj[ i ] );
562                                         if ( value === false ) {
563                                                 break;
564                                         }
565                                 }
566                         } else {
567                                 for ( i in obj ) {
568                                         value = callback.call( obj[ i ], i, obj[ i ] );
570                                         if ( value === false ) {
571                                                 break;
572                                         }
573                                 }
574                         }
575                 }
577                 return obj;
578         },
580         trim: function( text ) {
581                 return text == null ? "" : core_trim.call( text );
582         },
584         // results is for internal usage only
585         makeArray: function( arr, results ) {
586                 var ret = results || [];
588                 if ( arr != null ) {
589                         if ( isArraylike( Object(arr) ) ) {
590                                 jQuery.merge( ret,
591                                         typeof arr === "string" ?
592                                         [ arr ] : arr
593                                 );
594                         } else {
595                                 core_push.call( ret, arr );
596                         }
597                 }
599                 return ret;
600         },
602         inArray: function( elem, arr, i ) {
603                 return core_indexOf.call( arr, elem, i );
604         },
606         merge: function( first, second ) {
607                 var l = second.length,
608                         i = first.length,
609                         j = 0;
611                 if ( typeof l === "number" ) {
612                         for ( ; j < l; j++ ) {
613                                 first[ i++ ] = second[ j ];
614                         }
615                 } else {
616                         while ( second[j] !== undefined ) {
617                                 first[ i++ ] = second[ j++ ];
618                         }
619                 }
621                 first.length = i;
623                 return first;
624         },
626         grep: function( elems, callback, inv ) {
627                 var retVal,
628                         ret = [],
629                         i = 0,
630                         length = elems.length;
631                 inv = !!inv;
633                 // Go through the array, only saving the items
634                 // that pass the validator function
635                 for ( ; i < length; i++ ) {
636                         retVal = !!callback( elems[ i ], i );
637                         if ( inv !== retVal ) {
638                                 ret.push( elems[ i ] );
639                         }
640                 }
642                 return ret;
643         },
645         // arg is for internal usage only
646         map: function( elems, callback, arg ) {
647                 var value,
648                         i = 0,
649                         length = elems.length,
650                         isArray = isArraylike( elems ),
651                         ret = [];
653                 // Go through the array, translating each of the items to their
654                 if ( isArray ) {
655                         for ( ; i < length; i++ ) {
656                                 value = callback( elems[ i ], i, arg );
658                                 if ( value != null ) {
659                                         ret[ ret.length ] = value;
660                                 }
661                         }
663                 // Go through every key on the object,
664                 } else {
665                         for ( i in elems ) {
666                                 value = callback( elems[ i ], i, arg );
668                                 if ( value != null ) {
669                                         ret[ ret.length ] = value;
670                                 }
671                         }
672                 }
674                 // Flatten any nested arrays
675                 return core_concat.apply( [], ret );
676         },
678         // A global GUID counter for objects
679         guid: 1,
681         // Bind a function to a context, optionally partially applying any
682         // arguments.
683         proxy: function( fn, context ) {
684                 var tmp, args, proxy;
686                 if ( typeof context === "string" ) {
687                         tmp = fn[ context ];
688                         context = fn;
689                         fn = tmp;
690                 }
692                 // Quick check to determine if target is callable, in the spec
693                 // this throws a TypeError, but we will just return undefined.
694                 if ( !jQuery.isFunction( fn ) ) {
695                         return undefined;
696                 }
698                 // Simulated bind
699                 args = core_slice.call( arguments, 2 );
700                 proxy = function() {
701                         return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
702                 };
704                 // Set the guid of unique handler to the same of original handler, so it can be removed
705                 proxy.guid = fn.guid = fn.guid || jQuery.guid++;
707                 return proxy;
708         },
710         // Multifunctional method to get and set values of a collection
711         // The value/s can optionally be executed if it's a function
712         access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
713                 var i = 0,
714                         length = elems.length,
715                         bulk = key == null;
717                 // Sets many values
718                 if ( jQuery.type( key ) === "object" ) {
719                         chainable = true;
720                         for ( i in key ) {
721                                 jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
722                         }
724                 // Sets one value
725                 } else if ( value !== undefined ) {
726                         chainable = true;
728                         if ( !jQuery.isFunction( value ) ) {
729                                 raw = true;
730                         }
732                         if ( bulk ) {
733                                 // Bulk operations run against the entire set
734                                 if ( raw ) {
735                                         fn.call( elems, value );
736                                         fn = null;
738                                 // ...except when executing function values
739                                 } else {
740                                         bulk = fn;
741                                         fn = function( elem, key, value ) {
742                                                 return bulk.call( jQuery( elem ), value );
743                                         };
744                                 }
745                         }
747                         if ( fn ) {
748                                 for ( ; i < length; i++ ) {
749                                         fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
750                                 }
751                         }
752                 }
754                 return chainable ?
755                         elems :
757                         // Gets
758                         bulk ?
759                                 fn.call( elems ) :
760                                 length ? fn( elems[0], key ) : emptyGet;
761         },
763         now: Date.now
766 jQuery.ready.promise = function( obj ) {
767         if ( !readyList ) {
769                 readyList = jQuery.Deferred();
771                 // Catch cases where $(document).ready() is called after the browser event has already occurred.
772                 // we once tried to use readyState "interactive" here, but it caused issues like the one
773                 // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
774                 if ( document.readyState === "complete" ) {
775                         // Handle it asynchronously to allow scripts the opportunity to delay ready
776                         setTimeout( jQuery.ready );
778                 // Standards-based browsers support DOMContentLoaded
779                 } else {
780                         // Use the handy event callback
781                         document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
783                         // A fallback to window.onload, that will always work
784                         window.addEventListener( "load", jQuery.ready, false );
785                 }
786         }
787         return readyList.promise( obj );
790 // Populate the class2type map
791 jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
792         class2type[ "[object " + name + "]" ] = name.toLowerCase();
795 function isArraylike( obj ) {
796         var length = obj.length,
797                 type = jQuery.type( obj );
799         if ( jQuery.isWindow( obj ) ) {
800                 return false;
801         }
803         if ( obj.nodeType === 1 && length ) {
804                 return true;
805         }
807         return type === "array" || type !== "function" &&
808                 ( length === 0 ||
809                 typeof length === "number" && length > 0 && ( length - 1 ) in obj );
812 // All jQuery objects should point back to these
813 rootjQuery = jQuery(document);