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