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