cloneCopyEvent; jQuery.clone() review
[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 (html5)
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( events, deepData ) {
187                 return this.map( function () {
188                         return jQuery.clone( this, events == null ? true : events, deepData == null ? true : deepData );
189                 });
190         },
191
192         html: function( value ) {
193                 if ( value === undefined ) {
194                         return this[0] && this[0].nodeType === 1 ?
195                                 this[0].innerHTML.replace(rinlinejQuery, "") :
196                                 null;
197
198                 // See if we can take a shortcut and just use innerHTML
199                 } else if ( typeof value === "string" && !rnocache.test( value ) &&
200                         (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
201                         !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
202
203                         value = value.replace(rxhtmlTag, "<$1></$2>");
204
205                         try {
206                                 for ( var i = 0, l = this.length; i < l; i++ ) {
207                                         // Remove element nodes and prevent memory leaks
208                                         if ( this[i].nodeType === 1 ) {
209                                                 jQuery.cleanData( this[i].getElementsByTagName("*") );
210                                                 this[i].innerHTML = value;
211                                         }
212                                 }
213
214                         // If using innerHTML throws an exception, use the fallback method
215                         } catch(e) {
216                                 this.empty().append( value );
217                         }
218
219                 } else if ( jQuery.isFunction( value ) ) {
220                         this.each(function(i){
221                                 var self = jQuery( this );
222
223                                 self.html( value.call(this, i, self.html()) );
224                         });
225
226                 } else {
227                         this.empty().append( value );
228                 }
229
230                 return this;
231         },
232
233         replaceWith: function( value ) {
234                 if ( this[0] && this[0].parentNode ) {
235                         // Make sure that the elements are removed from the DOM before they are inserted
236                         // this can help fix replacing a parent with child elements
237                         if ( jQuery.isFunction( value ) ) {
238                                 return this.each(function(i) {
239                                         var self = jQuery(this), old = self.html();
240                                         self.replaceWith( value.call( this, i, old ) );
241                                 });
242                         }
243
244                         if ( typeof value !== "string" ) {
245                                 value = jQuery( value ).detach();
246                         }
247
248                         return this.each(function() {
249                                 var next = this.nextSibling,
250                                         parent = this.parentNode;
251
252                                 jQuery( this ).remove();
253
254                                 if ( next ) {
255                                         jQuery(next).before( value );
256                                 } else {
257                                         jQuery(parent).append( value );
258                                 }
259                         });
260                 } else {
261                         return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
262                 }
263         },
264
265         detach: function( selector ) {
266                 return this.remove( selector, true );
267         },
268
269         domManip: function( args, table, callback ) {
270                 var results, first, fragment, parent,
271                         value = args[0],
272                         scripts = [];
273
274                 // We can't cloneNode fragments that contain checked, in WebKit
275                 if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
276                         return this.each(function() {
277                                 jQuery(this).domManip( args, table, callback, true );
278                         });
279                 }
280
281                 if ( jQuery.isFunction(value) ) {
282                         return this.each(function(i) {
283                                 var self = jQuery(this);
284                                 args[0] = value.call(this, i, table ? self.html() : undefined);
285                                 self.domManip( args, table, callback );
286                         });
287                 }
288
289                 if ( this[0] ) {
290                         parent = value && value.parentNode;
291
292                         // If we're in a fragment, just use that instead of building a new one
293                         if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
294                                 results = { fragment: parent };
295
296                         } else {
297                                 results = jQuery.buildFragment( args, this, scripts );
298                         }
299
300                         fragment = results.fragment;
301
302                         if ( fragment.childNodes.length === 1 ) {
303                                 first = fragment = fragment.firstChild;
304                         } else {
305                                 first = fragment.firstChild;
306                         }
307
308                         if ( first ) {
309                                 table = table && jQuery.nodeName( first, "tr" );
310
311                                 for ( var i = 0, l = this.length; i < l; i++ ) {
312                                         callback.call(
313                                                 table ?
314                                                         root(this[i], first) :
315                                                         this[i],
316                                                 i > 0 || results.cacheable || (this.length > 1 && i > 0) ?
317                                                         jQuery.clone( fragment, true, true ) :
318                                                         fragment
319                                         );
320                                 }
321                         }
322
323                         if ( scripts.length ) {
324                                 jQuery.each( scripts, evalScript );
325                         }
326                 }
327
328                 return this;
329         }
330 });
331
332 function root( elem, cur ) {
333         return jQuery.nodeName(elem, "table") ?
334                 (elem.getElementsByTagName("tbody")[0] ||
335                 elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
336                 elem;
337 }
338
339 function cloneCopyEvent( src, dest ) {
340
341         if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
342                 return;
343         }
344
345         var internalKey = jQuery.expando,
346                         oldData = jQuery.data( src ),
347                         curData = jQuery.data( dest, oldData );
348
349         // Switch to use the internal data object, if it exists, for the next
350         // stage of data copying
351         if ( (oldData = oldData[ internalKey ]) ) {
352                 var events = oldData.events;
353                                 curData = curData[ internalKey ] = jQuery.extend({}, oldData);
354
355                 if ( events ) {
356                         delete curData.handle;
357                         curData.events = {};
358
359                         for ( var type in events ) {
360                                 for ( var i = 0, l = events[ type ].length; i < l; i++ ) {
361                                         jQuery.event.add( dest, type, events[ type ][ i ], events[ type ][ i ].data );
362                                 }
363                         }
364                 }
365         }
366 }
367
368 function cloneFixAttributes(src, dest) {
369         // We do not need to do anything for non-Elements
370         if ( dest.nodeType !== 1 ) {
371                 return;
372         }
373
374         var nodeName = dest.nodeName.toLowerCase();
375
376         // clearAttributes removes the attributes, which we don't want,
377         // but also removes the attachEvent events, which we *do* want
378         dest.clearAttributes();
379
380         // mergeAttributes, in contrast, only merges back on the
381         // original attributes, not the events
382         dest.mergeAttributes(src);
383
384         // IE6-8 fail to clone children inside object elements that use
385         // the proprietary classid attribute value (rather than the type
386         // attribute) to identify the type of content to display
387         if ( nodeName === "object" ) {
388                 dest.outerHTML = src.outerHTML;
389
390         } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
391                 // IE6-8 fails to persist the checked state of a cloned checkbox
392                 // or radio button. Worse, IE6-7 fail to give the cloned element
393                 // a checked appearance if the defaultChecked value isn't also set
394                 if ( src.checked ) {
395                         dest.defaultChecked = dest.checked = src.checked;
396                 }
397
398                 // IE6-7 get confused and end up setting the value of a cloned
399                 // checkbox/radio button to an empty string instead of "on"
400                 if ( dest.value !== src.value ) {
401                         dest.value = src.value;
402                 }
403
404         // IE6-8 fails to return the selected option to the default selected
405         // state when cloning options
406         } else if ( nodeName === "option" ) {
407                 dest.selected = src.defaultSelected;
408
409         // IE6-8 fails to set the defaultValue to the correct value when
410         // cloning other types of input fields
411         } else if ( nodeName === "input" || nodeName === "textarea" ) {
412                 dest.defaultValue = src.defaultValue;
413         }
414
415         // Event data gets referenced instead of copied if the expando
416         // gets copied too
417         dest.removeAttribute( jQuery.expando );
418 }
419
420 jQuery.buildFragment = function( args, nodes, scripts ) {
421         var fragment, cacheable, cacheresults,
422                 doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
423
424         // Only cache "small" (1/2 KB) HTML strings that are associated with the main document
425         // Cloning options loses the selected state, so don't cache them
426         // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
427         // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
428         if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
429                 args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
430
431                 cacheable = true;
432                 cacheresults = jQuery.fragments[ args[0] ];
433                 if ( cacheresults ) {
434                         if ( cacheresults !== 1 ) {
435                                 fragment = cacheresults;
436                         }
437                 }
438         }
439
440         if ( !fragment ) {
441                 fragment = doc.createDocumentFragment();
442                 jQuery.clean( args, doc, fragment, scripts );
443         }
444
445         if ( cacheable ) {
446                 jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
447         }
448
449         return { fragment: fragment, cacheable: cacheable };
450 };
451
452 jQuery.fragments = {};
453
454 jQuery.each({
455         appendTo: "append",
456         prependTo: "prepend",
457         insertBefore: "before",
458         insertAfter: "after",
459         replaceAll: "replaceWith"
460 }, function( name, original ) {
461         jQuery.fn[ name ] = function( selector ) {
462                 var ret = [],
463                         insert = jQuery( selector ),
464                         parent = this.length === 1 && this[0].parentNode;
465
466                 if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
467                         insert[ original ]( this[0] );
468                         return this;
469
470                 } else {
471                         for ( var i = 0, l = insert.length; i < l; i++ ) {
472                                 var elems = (i > 0 ? this.clone(true) : this).get();
473                                 jQuery( insert[i] )[ original ]( elems );
474                                 ret = ret.concat( elems );
475                         }
476
477                         return this.pushStack( ret, name, insert.selector );
478                 }
479         };
480 });
481
482 jQuery.extend({
483         clone: function( elem, dataAndEvents, deepCloneDataAndEvents ) {
484
485                 var clone = elem.cloneNode(true), 
486                                 srcElements, 
487                                 destElements;
488
489                 if ( !jQuery.support.noCloneEvent && ( elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
490                         // IE copies events bound via attachEvent when using cloneNode.
491                         // Calling detachEvent on the clone will also remove the events
492                         // from the original. In order to get around this, we use some
493                         // proprietary methods to clear the events. Thanks to MooTools
494                         // guys for this hotness.
495
496                         // Using Sizzle here is crazy slow, so we use getElementsByTagName
497                         // instead
498                         srcElements = elem.getElementsByTagName("*");
499                         destElements = clone.getElementsByTagName("*");
500
501                         // Weird iteration because IE will replace the length property
502                         // with an element if you are cloning the body and one of the
503                         // elements on the page has a name or id of "length"
504                         for ( var i = 0; srcElements[i]; ++i ) {
505                                 cloneFixAttributes( srcElements[i], destElements[i] );
506                         }
507
508                         cloneFixAttributes( elem, clone );
509                 }
510
511                 // Copy the events from the original to the clone
512                 if ( dataAndEvents === true ) {
513
514                         cloneCopyEvent( elem , clone );
515
516                         if ( deepCloneDataAndEvents === true && "getElementsByTagName" in elem ) {
517
518                                 srcElements = elem.getElementsByTagName("*");
519                                 destElements = clone.getElementsByTagName("*");
520
521                                 if ( srcElements.length ) {
522                                         for ( var i = 0; i < srcElements.length; ++i ) {
523                                                 cloneCopyEvent( srcElements[i], destElements[i] );
524                                         }
525                                 }
526                         }
527                 }
528                 // Return the cloned set
529                 return clone;
530   },
531         clean: function( elems, context, fragment, scripts ) {
532                 context = context || document;
533
534                 // !context.createElement fails in IE with an error but returns typeof 'object'
535                 if ( typeof context.createElement === "undefined" ) {
536                         context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
537                 }
538
539                 var ret = [];
540
541                 for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
542                         if ( typeof elem === "number" ) {
543                                 elem += "";
544                         }
545
546                         if ( !elem ) {
547                                 continue;
548                         }
549
550                         // Convert html string into DOM nodes
551                         if ( typeof elem === "string" && !rhtml.test( elem ) ) {
552                                 elem = context.createTextNode( elem );
553
554                         } else if ( typeof elem === "string" ) {
555                                 // Fix "XHTML"-style tags in all browsers
556                                 elem = elem.replace(rxhtmlTag, "<$1></$2>");
557
558                                 // Trim whitespace, otherwise indexOf won't work as expected
559                                 var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
560                                         wrap = wrapMap[ tag ] || wrapMap._default,
561                                         depth = wrap[0],
562                                         div = context.createElement("div");
563
564                                 // Go to html and back, then peel off extra wrappers
565                                 div.innerHTML = wrap[1] + elem + wrap[2];
566
567                                 // Move to the right depth
568                                 while ( depth-- ) {
569                                         div = div.lastChild;
570                                 }
571
572                                 // Remove IE's autoinserted <tbody> from table fragments
573                                 if ( !jQuery.support.tbody ) {
574
575                                         // String was a <table>, *may* have spurious <tbody>
576                                         var hasBody = rtbody.test(elem),
577                                                 tbody = tag === "table" && !hasBody ?
578                                                         div.firstChild && div.firstChild.childNodes :
579
580                                                         // String was a bare <thead> or <tfoot>
581                                                         wrap[1] === "<table>" && !hasBody ?
582                                                                 div.childNodes :
583                                                                 [];
584
585                                         for ( var j = tbody.length - 1; j >= 0 ; --j ) {
586                                                 if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
587                                                         tbody[ j ].parentNode.removeChild( tbody[ j ] );
588                                                 }
589                                         }
590
591                                 }
592
593                                 // IE completely kills leading whitespace when innerHTML is used
594                                 if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
595                                         div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
596                                 }
597
598                                 elem = div.childNodes;
599                         }
600
601                         if ( elem.nodeType ) {
602                                 ret.push( elem );
603                         } else {
604                                 ret = jQuery.merge( ret, elem );
605                         }
606                 }
607
608                 if ( fragment ) {
609                         for ( i = 0; ret[i]; i++ ) {
610                                 if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
611                                         scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
612
613                                 } else {
614                                         if ( ret[i].nodeType === 1 ) {
615                                                 ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
616                                         }
617                                         fragment.appendChild( ret[i] );
618                                 }
619                         }
620                 }
621
622                 return ret;
623         },
624
625         cleanData: function( elems ) {
626                 var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special,
627                         deleteExpando = jQuery.support.deleteExpando;
628
629                 for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
630                         if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
631                                 continue;
632                         }
633
634                         id = elem[ jQuery.expando ];
635
636                         if ( id ) {
637                                 data = cache[ id ] && cache[ id ][ internalKey ];
638
639                                 if ( data && data.events ) {
640                                         for ( var type in data.events ) {
641                                                 if ( special[ type ] ) {
642                                                         jQuery.event.remove( elem, type );
643
644                                                 // This is a shortcut to avoid jQuery.event.remove's overhead
645                                                 } else {
646                                                         jQuery.removeEvent( elem, type, data.handle );
647                                                 }
648                                         }
649
650                                         // Null the DOM reference to avoid IE6/7/8 leak (#7054)
651                                         if ( data.handle ) {
652                                                 data.handle.elem = null;
653                                         }
654                                 }
655
656                                 if ( deleteExpando ) {
657                                         delete elem[ jQuery.expando ];
658
659                                 } else if ( elem.removeAttribute ) {
660                                         elem.removeAttribute( jQuery.expando );
661                                 }
662
663                                 delete cache[ id ];
664                         }
665                 }
666         }
667 });
668
669 function evalScript( i, elem ) {
670         if ( elem.src ) {
671                 jQuery.ajax({
672                         url: elem.src,
673                         async: false,
674                         dataType: "script"
675                 });
676         } else {
677                 jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
678         }
679
680         if ( elem.parentNode ) {
681                 elem.parentNode.removeChild( elem );
682         }
683 }
684
685 })( jQuery );