Updating Sizzle submodule to bring in the latest commit.
[jquery.git] / src / manipulation.js
1 (function( jQuery ) {
2
3 var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
4         rleadingWhitespace = /^\s+/,
5         rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
6         rtagName = /<([\w:]+)/,
7         rtbody = /<tbody/i,
8         rhtml = /<|&#?\w+;/,
9         rnocache = /<(?:script|object|embed|option|style)/i,
10         // checked="checked" or checked
11         rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
12         wrapMap = {
13                 option: [ 1, "<select multiple='multiple'>", "</select>" ],
14                 legend: [ 1, "<fieldset>", "</fieldset>" ],
15                 thead: [ 1, "<table>", "</table>" ],
16                 tr: [ 2, "<table><tbody>", "</tbody></table>" ],
17                 td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
18                 col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
19                 area: [ 1, "<map>", "</map>" ],
20                 _default: [ 0, "", "" ]
21         };
22
23 wrapMap.optgroup = wrapMap.option;
24 wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
25 wrapMap.th = wrapMap.td;
26
27 // IE can't serialize <link> and <script> tags normally
28 if ( !jQuery.support.htmlSerialize ) {
29         wrapMap._default = [ 1, "div<div>", "</div>" ];
30 }
31
32 jQuery.fn.extend({
33         text: function( text ) {
34                 if ( jQuery.isFunction(text) ) {
35                         return this.each(function(i) {
36                                 var self = jQuery( this );
37
38                                 self.text( text.call(this, i, self.text()) );
39                         });
40                 }
41
42                 if ( typeof text !== "object" && text !== undefined ) {
43                         return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
44                 }
45
46                 return jQuery.text( this );
47         },
48
49         wrapAll: function( html ) {
50                 if ( jQuery.isFunction( html ) ) {
51                         return this.each(function(i) {
52                                 jQuery(this).wrapAll( html.call(this, i) );
53                         });
54                 }
55
56                 if ( this[0] ) {
57                         // The elements to wrap the target around
58                         var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
59
60                         if ( this[0].parentNode ) {
61                                 wrap.insertBefore( this[0] );
62                         }
63
64                         wrap.map(function() {
65                                 var elem = this;
66
67                                 while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
68                                         elem = elem.firstChild;
69                                 }
70
71                                 return elem;
72                         }).append(this);
73                 }
74
75                 return this;
76         },
77
78         wrapInner: function( html ) {
79                 if ( jQuery.isFunction( html ) ) {
80                         return this.each(function(i) {
81                                 jQuery(this).wrapInner( html.call(this, i) );
82                         });
83                 }
84
85                 return this.each(function() {
86                         var self = jQuery( this ),
87                                 contents = self.contents();
88
89                         if ( contents.length ) {
90                                 contents.wrapAll( html );
91
92                         } else {
93                                 self.append( html );
94                         }
95                 });
96         },
97
98         wrap: function( html ) {
99                 return this.each(function() {
100                         jQuery( this ).wrapAll( html );
101                 });
102         },
103
104         unwrap: function() {
105                 return this.parent().each(function() {
106                         if ( !jQuery.nodeName( this, "body" ) ) {
107                                 jQuery( this ).replaceWith( this.childNodes );
108                         }
109                 }).end();
110         },
111
112         append: function() {
113                 return this.domManip(arguments, true, function( elem ) {
114                         if ( this.nodeType === 1 ) {
115                                 this.appendChild( elem );
116                         }
117                 });
118         },
119
120         prepend: function() {
121                 return this.domManip(arguments, true, function( elem ) {
122                         if ( this.nodeType === 1 ) {
123                                 this.insertBefore( elem, this.firstChild );
124                         }
125                 });
126         },
127
128         before: function() {
129                 if ( this[0] && this[0].parentNode ) {
130                         return this.domManip(arguments, false, function( elem ) {
131                                 this.parentNode.insertBefore( elem, this );
132                         });
133                 } else if ( arguments.length ) {
134                         var set = jQuery(arguments[0]);
135                         set.push.apply( set, this.toArray() );
136                         return this.pushStack( set, "before", arguments );
137                 }
138         },
139
140         after: function() {
141                 if ( this[0] && this[0].parentNode ) {
142                         return this.domManip(arguments, false, function( elem ) {
143                                 this.parentNode.insertBefore( elem, this.nextSibling );
144                         });
145                 } else if ( arguments.length ) {
146                         var set = this.pushStack( this, "after", arguments );
147                         set.push.apply( set, jQuery(arguments[0]).toArray() );
148                         return set;
149                 }
150         },
151
152         // keepData is for internal use only--do not document
153         remove: function( selector, keepData ) {
154                 for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
155                         if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
156                                 if ( !keepData && elem.nodeType === 1 ) {
157                                         jQuery.cleanData( elem.getElementsByTagName("*") );
158                                         jQuery.cleanData( [ elem ] );
159                                 }
160
161                                 if ( elem.parentNode ) {
162                                         elem.parentNode.removeChild( elem );
163                                 }
164                         }
165                 }
166
167                 return this;
168         },
169
170         empty: function() {
171                 for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
172                         // Remove element nodes and prevent memory leaks
173                         if ( elem.nodeType === 1 ) {
174                                 jQuery.cleanData( elem.getElementsByTagName("*") );
175                         }
176
177                         // Remove any remaining nodes
178                         while ( elem.firstChild ) {
179                                 elem.removeChild( elem.firstChild );
180                         }
181                 }
182
183                 return this;
184         },
185
186         clone: function( dataAndEvents, deepDataAndEvents ) {
187                 dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
188                 deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
189
190                 return this.map( function () {
191                         return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
192                 });
193         },
194
195         html: function( value ) {
196                 if ( value === undefined ) {
197                         return this[0] && this[0].nodeType === 1 ?
198                                 this[0].innerHTML.replace(rinlinejQuery, "") :
199                                 null;
200
201                 // See if we can take a shortcut and just use innerHTML
202                 } else if ( typeof value === "string" && !rnocache.test( value ) &&
203                         (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
204                         !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
205
206                         value = value.replace(rxhtmlTag, "<$1></$2>");
207
208                         try {
209                                 for ( var i = 0, l = this.length; i < l; i++ ) {
210                                         // Remove element nodes and prevent memory leaks
211                                         if ( this[i].nodeType === 1 ) {
212                                                 jQuery.cleanData( this[i].getElementsByTagName("*") );
213                                                 this[i].innerHTML = value;
214                                         }
215                                 }
216
217                         // If using innerHTML throws an exception, use the fallback method
218                         } catch(e) {
219                                 this.empty().append( value );
220                         }
221
222                 } else if ( jQuery.isFunction( value ) ) {
223                         this.each(function(i){
224                                 var self = jQuery( this );
225
226                                 self.html( value.call(this, i, self.html()) );
227                         });
228
229                 } else {
230                         this.empty().append( value );
231                 }
232
233                 return this;
234         },
235
236         replaceWith: function( value ) {
237                 if ( this[0] && this[0].parentNode ) {
238                         // Make sure that the elements are removed from the DOM before they are inserted
239                         // this can help fix replacing a parent with child elements
240                         if ( jQuery.isFunction( value ) ) {
241                                 return this.each(function(i) {
242                                         var self = jQuery(this), old = self.html();
243                                         self.replaceWith( value.call( this, i, old ) );
244                                 });
245                         }
246
247                         if ( typeof value !== "string" ) {
248                                 value = jQuery( value ).detach();
249                         }
250
251                         return this.each(function() {
252                                 var next = this.nextSibling,
253                                         parent = this.parentNode;
254
255                                 jQuery( this ).remove();
256
257                                 if ( next ) {
258                                         jQuery(next).before( value );
259                                 } else {
260                                         jQuery(parent).append( value );
261                                 }
262                         });
263                 } else {
264                         return this.length ?
265                                 this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
266                                 this;
267                 }
268         },
269
270         detach: function( selector ) {
271                 return this.remove( selector, true );
272         },
273
274         domManip: function( args, table, callback ) {
275                 var results, first, fragment, parent,
276                         value = args[0],
277                         scripts = [];
278
279                 // We can't cloneNode fragments that contain checked, in WebKit
280                 if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
281                         return this.each(function() {
282                                 jQuery(this).domManip( args, table, callback, true );
283                         });
284                 }
285
286                 if ( jQuery.isFunction(value) ) {
287                         return this.each(function(i) {
288                                 var self = jQuery(this);
289                                 args[0] = value.call(this, i, table ? self.html() : undefined);
290                                 self.domManip( args, table, callback );
291                         });
292                 }
293
294                 if ( this[0] ) {
295                         parent = value && value.parentNode;
296
297                         // If we're in a fragment, just use that instead of building a new one
298                         if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
299                                 results = { fragment: parent };
300
301                         } else {
302                                 results = jQuery.buildFragment( args, this, scripts );
303                         }
304
305                         fragment = results.fragment;
306
307                         if ( fragment.childNodes.length === 1 ) {
308                                 first = fragment = fragment.firstChild;
309                         } else {
310                                 first = fragment.firstChild;
311                         }
312
313                         if ( first ) {
314                                 table = table && jQuery.nodeName( first, "tr" );
315
316                                 for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
317                                         callback.call(
318                                                 table ?
319                                                         root(this[i], first) :
320                                                         this[i],
321                                                 // Make sure that we do not leak memory by inadvertently discarding
322                                                 // the original fragment (which might have attached data) instead of
323                                                 // using it; in addition, use the original fragment object for the last
324                                                 // item instead of first because it can end up being emptied incorrectly
325                                                 // in certain situations (Bug #8070).
326                                                 // Fragments from the fragment cache must always be cloned and never used
327                                                 // in place.
328                                                 results.cacheable || (l > 1 && i < lastIndex) ?
329                                                         jQuery.clone( fragment, true, true ) :
330                                                         fragment
331                                         );
332                                 }
333                         }
334
335                         if ( scripts.length ) {
336                                 jQuery.each( scripts, evalScript );
337                         }
338                 }
339
340                 return this;
341         }
342 });
343
344 function root( elem, cur ) {
345         return jQuery.nodeName(elem, "table") ?
346                 (elem.getElementsByTagName("tbody")[0] ||
347                 elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
348                 elem;
349 }
350
351 function cloneCopyEvent( src, dest ) {
352
353         if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
354                 return;
355         }
356
357         var internalKey = jQuery.expando,
358                 oldData = jQuery.data( src ),
359                 curData = jQuery.data( dest, oldData );
360
361         // Switch to use the internal data object, if it exists, for the next
362         // stage of data copying
363         if ( (oldData = oldData[ internalKey ]) ) {
364                 var events = oldData.events;
365                                 curData = curData[ internalKey ] = jQuery.extend({}, oldData);
366
367                 if ( events ) {
368                         delete curData.handle;
369                         curData.events = {};
370
371                         for ( var type in events ) {
372                                 for ( var i = 0, l = events[ type ].length; i < l; i++ ) {
373                                         jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data );
374                                 }
375                         }
376                 }
377         }
378 }
379
380 function cloneFixAttributes(src, dest) {
381         // We do not need to do anything for non-Elements
382         if ( dest.nodeType !== 1 ) {
383                 return;
384         }
385
386         var nodeName = dest.nodeName.toLowerCase();
387
388         // clearAttributes removes the attributes, which we don't want,
389         // but also removes the attachEvent events, which we *do* want
390         dest.clearAttributes();
391
392         // mergeAttributes, in contrast, only merges back on the
393         // original attributes, not the events
394         dest.mergeAttributes(src);
395
396         // IE6-8 fail to clone children inside object elements that use
397         // the proprietary classid attribute value (rather than the type
398         // attribute) to identify the type of content to display
399         if ( nodeName === "object" ) {
400                 dest.outerHTML = src.outerHTML;
401
402         } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
403                 // IE6-8 fails to persist the checked state of a cloned checkbox
404                 // or radio button. Worse, IE6-7 fail to give the cloned element
405                 // a checked appearance if the defaultChecked value isn't also set
406                 if ( src.checked ) {
407                         dest.defaultChecked = dest.checked = src.checked;
408                 }
409
410                 // IE6-7 get confused and end up setting the value of a cloned
411                 // checkbox/radio button to an empty string instead of "on"
412                 if ( dest.value !== src.value ) {
413                         dest.value = src.value;
414                 }
415
416         // IE6-8 fails to return the selected option to the default selected
417         // state when cloning options
418         } else if ( nodeName === "option" ) {
419                 dest.selected = src.defaultSelected;
420
421         // IE6-8 fails to set the defaultValue to the correct value when
422         // cloning other types of input fields
423         } else if ( nodeName === "input" || nodeName === "textarea" ) {
424                 dest.defaultValue = src.defaultValue;
425         }
426
427         // Event data gets referenced instead of copied if the expando
428         // gets copied too
429         dest.removeAttribute( jQuery.expando );
430 }
431
432 jQuery.buildFragment = function( args, nodes, scripts ) {
433         var fragment, cacheable, cacheresults,
434                 doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
435
436         // Only cache "small" (1/2 KB) HTML strings that are associated with the main document
437         // Cloning options loses the selected state, so don't cache them
438         // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
439         // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
440         if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
441                 args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
442
443                 cacheable = true;
444                 cacheresults = jQuery.fragments[ args[0] ];
445                 if ( cacheresults ) {
446                         if ( cacheresults !== 1 ) {
447                                 fragment = cacheresults;
448                         }
449                 }
450         }
451
452         if ( !fragment ) {
453                 fragment = doc.createDocumentFragment();
454                 jQuery.clean( args, doc, fragment, scripts );
455         }
456
457         if ( cacheable ) {
458                 jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
459         }
460
461         return { fragment: fragment, cacheable: cacheable };
462 };
463
464 jQuery.fragments = {};
465
466 jQuery.each({
467         appendTo: "append",
468         prependTo: "prepend",
469         insertBefore: "before",
470         insertAfter: "after",
471         replaceAll: "replaceWith"
472 }, function( name, original ) {
473         jQuery.fn[ name ] = function( selector ) {
474                 var ret = [],
475                         insert = jQuery( selector ),
476                         parent = this.length === 1 && this[0].parentNode;
477
478                 if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
479                         insert[ original ]( this[0] );
480                         return this;
481
482                 } else {
483                         for ( var i = 0, l = insert.length; i < l; i++ ) {
484                                 var elems = (i > 0 ? this.clone(true) : this).get();
485                                 jQuery( insert[i] )[ original ]( elems );
486                                 ret = ret.concat( elems );
487                         }
488
489                         return this.pushStack( ret, name, insert.selector );
490                 }
491         };
492 });
493
494 function getAll( elem ) {
495         if ( "getElementsByTagName" in elem ) {
496                 return elem.getElementsByTagName( "*" );
497         
498         } else if ( "querySelectorAll" in elem ) {
499                 return elem.querySelectorAll( "*" );
500
501         } else {
502                 return [];
503         }
504 }
505
506 jQuery.extend({
507         clone: function( elem, dataAndEvents, deepDataAndEvents ) {
508                 var clone = elem.cloneNode(true),
509                                 srcElements,
510                                 destElements,
511                                 i;
512
513                 if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
514                                 (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
515                         // IE copies events bound via attachEvent when using cloneNode.
516                         // Calling detachEvent on the clone will also remove the events
517                         // from the original. In order to get around this, we use some
518                         // proprietary methods to clear the events. Thanks to MooTools
519                         // guys for this hotness.
520
521                         cloneFixAttributes( elem, clone );
522
523                         // Using Sizzle here is crazy slow, so we use getElementsByTagName
524                         // instead
525                         srcElements = getAll( elem );
526                         destElements = getAll( clone );
527
528                         // Weird iteration because IE will replace the length property
529                         // with an element if you are cloning the body and one of the
530                         // elements on the page has a name or id of "length"
531                         for ( i = 0; srcElements[i]; ++i ) {
532                                 cloneFixAttributes( srcElements[i], destElements[i] );
533                         }
534                 }
535
536                 // Copy the events from the original to the clone
537                 if ( dataAndEvents ) {
538                         cloneCopyEvent( elem, clone );
539
540                         if ( deepDataAndEvents ) {
541                                 srcElements = getAll( elem );
542                                 destElements = getAll( clone );
543
544                                 for ( i = 0; srcElements[i]; ++i ) {
545                                         cloneCopyEvent( srcElements[i], destElements[i] );
546                                 }
547                         }
548                 }
549
550                 // Return the cloned set
551                 return clone;
552 },
553         clean: function( elems, context, fragment, scripts ) {
554                 context = context || document;
555
556                 // !context.createElement fails in IE with an error but returns typeof 'object'
557                 if ( typeof context.createElement === "undefined" ) {
558                         context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
559                 }
560
561                 var ret = [];
562
563                 for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
564                         if ( typeof elem === "number" ) {
565                                 elem += "";
566                         }
567
568                         if ( !elem ) {
569                                 continue;
570                         }
571
572                         // Convert html string into DOM nodes
573                         if ( typeof elem === "string" && !rhtml.test( elem ) ) {
574                                 elem = context.createTextNode( elem );
575
576                         } else if ( typeof elem === "string" ) {
577                                 // Fix "XHTML"-style tags in all browsers
578                                 elem = elem.replace(rxhtmlTag, "<$1></$2>");
579
580                                 // Trim whitespace, otherwise indexOf won't work as expected
581                                 var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
582                                         wrap = wrapMap[ tag ] || wrapMap._default,
583                                         depth = wrap[0],
584                                         div = context.createElement("div");
585
586                                 // Go to html and back, then peel off extra wrappers
587                                 div.innerHTML = wrap[1] + elem + wrap[2];
588
589                                 // Move to the right depth
590                                 while ( depth-- ) {
591                                         div = div.lastChild;
592                                 }
593
594                                 // Remove IE's autoinserted <tbody> from table fragments
595                                 if ( !jQuery.support.tbody ) {
596
597                                         // String was a <table>, *may* have spurious <tbody>
598                                         var hasBody = rtbody.test(elem),
599                                                 tbody = tag === "table" && !hasBody ?
600                                                         div.firstChild && div.firstChild.childNodes :
601
602                                                         // String was a bare <thead> or <tfoot>
603                                                         wrap[1] === "<table>" && !hasBody ?
604                                                                 div.childNodes :
605                                                                 [];
606
607                                         for ( var j = tbody.length - 1; j >= 0 ; --j ) {
608                                                 if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
609                                                         tbody[ j ].parentNode.removeChild( tbody[ j ] );
610                                                 }
611                                         }
612
613                                 }
614
615                                 // IE completely kills leading whitespace when innerHTML is used
616                                 if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
617                                         div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
618                                 }
619
620                                 elem = div.childNodes;
621                         }
622
623                         if ( elem.nodeType ) {
624                                 ret.push( elem );
625                         } else {
626                                 ret = jQuery.merge( ret, elem );
627                         }
628                 }
629
630                 if ( fragment ) {
631                         for ( i = 0; ret[i]; i++ ) {
632                                 if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
633                                         scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
634
635                                 } else {
636                                         if ( ret[i].nodeType === 1 ) {
637                                                 ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
638                                         }
639                                         fragment.appendChild( ret[i] );
640                                 }
641                         }
642                 }
643
644                 return ret;
645         },
646
647         cleanData: function( elems ) {
648                 var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special,
649                         deleteExpando = jQuery.support.deleteExpando;
650
651                 for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
652                         if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
653                                 continue;
654                         }
655
656                         id = elem[ jQuery.expando ];
657
658                         if ( id ) {
659                                 data = cache[ id ] && cache[ id ][ internalKey ];
660
661                                 if ( data && data.events ) {
662                                         for ( var type in data.events ) {
663                                                 if ( special[ type ] ) {
664                                                         jQuery.event.remove( elem, type );
665
666                                                 // This is a shortcut to avoid jQuery.event.remove's overhead
667                                                 } else {
668                                                         jQuery.removeEvent( elem, type, data.handle );
669                                                 }
670                                         }
671
672                                         // Null the DOM reference to avoid IE6/7/8 leak (#7054)
673                                         if ( data.handle ) {
674                                                 data.handle.elem = null;
675                                         }
676                                 }
677
678                                 if ( deleteExpando ) {
679                                         delete elem[ jQuery.expando ];
680
681                                 } else if ( elem.removeAttribute ) {
682                                         elem.removeAttribute( jQuery.expando );
683                                 }
684
685                                 delete cache[ id ];
686                         }
687                 }
688         }
689 });
690
691 function evalScript( i, elem ) {
692         if ( elem.src ) {
693                 jQuery.ajax({
694                         url: elem.src,
695                         async: false,
696                         dataType: "script"
697                 });
698         } else {
699                 jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
700         }
701
702         if ( elem.parentNode ) {
703                 elem.parentNode.removeChild( elem );
704         }
705 }
706
707 })( jQuery );