Made .clone(true) also copy over element data. Fixes #4191.
[jquery.git] / src / manipulation.js
1 var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
2         rleadingWhitespace = /^\s+/,
3         rxhtmlTag = /(<([\w:]+)[^>]*?)\/>/g,
4         rselfClosing = /^(?:abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i,
5         rtagName = /<([\w:]+)/,
6         rtbody = /<tbody/i,
7         rhtml = /<|&\w+;/,
8         fcloseTag = function(all, front, tag){
9                 return rselfClosing.test(tag) ?
10                         all :
11                         front + "></" + tag + ">";
12         },
13         wrapMap = {
14                 option: [ 1, "<select multiple='multiple'>", "</select>" ],
15                 legend: [ 1, "<fieldset>", "</fieldset>" ],
16                 thead: [ 1, "<table>", "</table>" ],
17                 tr: [ 2, "<table><tbody>", "</tbody></table>" ],
18                 td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
19                 col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
20                 area: [ 1, "<map>", "</map>" ],
21                 _default: [ 0, "", "" ]
22         };
23
24 wrapMap.optgroup = wrapMap.option;
25 wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
26 wrapMap.th = wrapMap.td;
27
28 // IE can't serialize <link> and <script> tags normally
29 if ( !jQuery.support.htmlSerialize ) {
30         wrapMap._default = [ 1, "div<div>", "</div>" ];
31 }
32
33 jQuery.fn.extend({
34         text: function( text ) {
35                 if ( typeof text !== "object" && text !== undefined ) {
36                         return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
37                 }
38
39                 return jQuery.getText( this );
40         },
41
42         wrapAll: function( html ) {
43                 if ( jQuery.isFunction( html ) ) {
44                         return this.each(function() {
45                                 jQuery(this).wrapAll( html.apply(this, arguments) );
46                         });
47                 }
48
49                 if ( this[0] ) {
50                         // The elements to wrap the target around
51                         var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
52
53                         if ( this[0].parentNode ) {
54                                 wrap.insertBefore( this[0] );
55                         }
56
57                         wrap.map(function(){
58                                 var elem = this;
59
60                                 while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
61                                         elem = elem.firstChild;
62                                 }
63
64                                 return elem;
65                         }).append(this);
66                 }
67
68                 return this;
69         },
70
71         wrapInner: function( html ) {
72                 return this.each(function(){
73                         jQuery( this ).contents().wrapAll( html );
74                 });
75         },
76
77         wrap: function( html ) {
78                 return this.each(function(){
79                         jQuery( this ).wrapAll( html );
80                 });
81         },
82
83         unwrap: function() {
84                 return this.parent().each(function(){
85                         if ( !jQuery.nodeName( this, "body" ) ) {
86                                 jQuery( this ).replaceWith( this.childNodes );
87                         }
88                 }).end();
89         },
90         
91         append: function() {
92                 return this.domManip(arguments, true, function(elem){
93                         if ( this.nodeType === 1 ) {
94                                 this.appendChild( elem );
95                         }
96                 });
97         },
98
99         prepend: function() {
100                 return this.domManip(arguments, true, function(elem){
101                         if ( this.nodeType === 1 ) {
102                                 this.insertBefore( elem, this.firstChild );
103                         }
104                 });
105         },
106
107         before: function() {
108                 if ( this[0] && this[0].parentNode ) {
109                         return this.domManip(arguments, false, function(elem){
110                                 this.parentNode.insertBefore( elem, this );
111                         });
112                 } else if ( arguments.length ) {
113                         var set = jQuery(arguments[0]);
114                         set.push.apply( set, this.toArray() );
115                         return this.pushStack( set, "before", arguments );
116                 }
117         },
118
119         after: function() {
120                 if ( this[0] && this[0].parentNode ) {
121                         return this.domManip(arguments, false, function(elem){
122                                 this.parentNode.insertBefore( elem, this.nextSibling );
123                         });
124                 } else if ( arguments.length ) {
125                         var set = this.pushStack( this, "after", arguments );
126                         set.push.apply( set, jQuery(arguments[0]).toArray() );
127                         return set;
128                 }
129         },
130
131         clone: function( events ) {
132                 // Do the clone
133                 var ret = this.map(function(){
134                         if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
135                                 // IE copies events bound via attachEvent when
136                                 // using cloneNode. Calling detachEvent on the
137                                 // clone will also remove the events from the orignal
138                                 // In order to get around this, we use innerHTML.
139                                 // Unfortunately, this means some modifications to
140                                 // attributes in IE that are actually only stored
141                                 // as properties will not be copied (such as the
142                                 // the name attribute on an input).
143                                 var html = this.outerHTML, ownerDocument = this.ownerDocument;
144                                 if ( !html ) {
145                                         var div = ownerDocument.createElement("div");
146                                         div.appendChild( this.cloneNode(true) );
147                                         html = div.innerHTML;
148                                 }
149
150                                 return jQuery.clean([html.replace(rinlinejQuery, "")
151                                         .replace(rleadingWhitespace, "")], ownerDocument)[0];
152                         } else {
153                                 return this.cloneNode(true);
154                         }
155                 });
156
157                 // Copy the events from the original to the clone
158                 if ( events === true ) {
159                         cloneCopyEvent( this, ret );
160                         cloneCopyEvent( this.find("*"), ret.find("*") );
161                 }
162
163                 // Return the cloned set
164                 return ret;
165         },
166
167         html: function( value ) {
168                 if ( value === undefined ) {
169                         return this[0] ?
170                                 this[0].innerHTML.replace(rinlinejQuery, "") :
171                                 null;
172
173                 // See if we can take a shortcut and just use innerHTML
174                 } else if ( typeof value === "string" && !/<script/i.test( value ) &&
175                         (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
176                         !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
177
178                         try {
179                                 for ( var i = 0, l = this.length; i < l; i++ ) {
180                                         // Remove element nodes and prevent memory leaks
181                                         if ( this[i].nodeType === 1 ) {
182                                                 cleanData( this[i].getElementsByTagName("*") );
183                                                 this[i].innerHTML = value;
184                                         }
185                                 }
186
187                         // If using innerHTML throws an exception, use the fallback method
188                         } catch(e) {
189                                 this.empty().append( value );
190                         }
191
192                 } else {
193                         this.empty().append( value );
194                 }
195
196                 return this;
197         },
198
199         replaceWith: function( value ) {
200                 if ( this[0] && this[0].parentNode ) {
201                         return this.each(function(){
202                                 var next = this.nextSibling, parent = this.parentNode;
203
204                                 jQuery(this).remove();
205
206                                 if ( next ) {
207                                         jQuery(next).before( value );
208                                 } else {
209                                         jQuery(parent).append( value );
210                                 }
211                         });
212                 } else {
213                         return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
214                 }
215         },
216
217         detach: function( selector ) {
218                 return this.remove( selector, true );
219         },
220
221         domManip: function( args, table, callback ) {
222                 var results, first, value = args[0], scripts = [];
223
224                 if ( jQuery.isFunction(value) ) {
225                         return this.each(function() {
226                                 args[0] = value.call(this);
227                                 return jQuery(this).domManip( args, table, callback );
228                         });
229                 }
230
231                 if ( this[0] ) {
232                         // If we're in a fragment, just use that instead of building a new one
233                         if ( args[0] && args[0].parentNode && args[0].parentNode.nodeType === 11 ) {
234                                 results = { fragment: args[0].parentNode };
235                         } else {
236                                 results = buildFragment( args, this, scripts );
237                         }
238
239                         first = results.fragment.firstChild;
240
241                         if ( first ) {
242                                 table = table && jQuery.nodeName( first, "tr" );
243
244                                 for ( var i = 0, l = this.length; i < l; i++ ) {
245                                         callback.call(
246                                                 table ?
247                                                         root(this[i], first) :
248                                                         this[i],
249                                                 results.cacheable || this.length > 1 || i > 0 ?
250                                                         results.fragment.cloneNode(true) :
251                                                         results.fragment
252                                         );
253                                 }
254                         }
255
256                         if ( scripts ) {
257                                 jQuery.each( scripts, evalScript );
258                         }
259                 }
260
261                 return this;
262
263                 function root( elem, cur ) {
264                         return jQuery.nodeName(elem, "table") ?
265                                 (elem.getElementsByTagName("tbody")[0] ||
266                                 elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
267                                 elem;
268                 }
269         }
270 });
271
272 function cloneCopyEvent(orig, ret) {
273         var i = 0;
274
275         ret.each(function(){
276                 if ( this.nodeName !== orig[i].nodeName ) {
277                         return;
278                 }
279
280                 jQuery.data( this, jQuery.data( orig[i++] ) );
281         });
282 }
283
284 function buildFragment(args, nodes, scripts){
285         var fragment, cacheable, cached, cacheresults, doc;
286
287         if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && args[0].indexOf("<option") < 0 ) {
288                 cacheable = true;
289                 cacheresults = jQuery.fragments[ args[0] ];
290                 if ( cacheresults ) {
291                         if ( cacheresults !== 1 ) {
292                                 fragment = cacheresults;
293                         }
294                         cached = true;
295                 }
296         }
297
298         if ( !fragment ) {
299                 doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
300                 fragment = doc.createDocumentFragment();
301                 jQuery.clean( args, doc, fragment, scripts );
302         }
303
304         if ( cacheable ) {
305                 jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
306         }
307
308         return { fragment: fragment, cacheable: cacheable };
309 }
310
311 jQuery.fragments = {};
312
313 jQuery.each({
314         appendTo: "append",
315         prependTo: "prepend",
316         insertBefore: "before",
317         insertAfter: "after",
318         replaceAll: "replaceWith"
319 }, function(name, original){
320         jQuery.fn[ name ] = function( selector ) {
321                 var ret = [], insert = jQuery( selector );
322
323                 for ( var i = 0, l = insert.length; i < l; i++ ) {
324                         var elems = (i > 0 ? this.clone(true) : this).get();
325                         jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
326                         ret = ret.concat( elems );
327                 }
328                 return this.pushStack( ret, name, insert.selector );
329         };
330 });
331
332 jQuery.each({
333         // keepData is for internal use only--do not document
334         remove: function( selector, keepData ) {
335                 if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
336                         if ( !keepData && this.nodeType === 1 ) {
337                                 cleanData( this.getElementsByTagName("*") );
338                                 cleanData( [ this ] );
339                         }
340
341                         if ( this.parentNode ) {
342                                  this.parentNode.removeChild( this );
343                         }
344                 }
345         },
346
347         empty: function() {
348                 // Remove element nodes and prevent memory leaks
349                 if ( this.nodeType === 1 ) {
350                         cleanData( this.getElementsByTagName("*") );
351                 }
352
353                 // Remove any remaining nodes
354                 while ( this.firstChild ) {
355                         this.removeChild( this.firstChild );
356                 }
357         }
358 }, function(name, fn){
359         jQuery.fn[ name ] = function(){
360                 return this.each( fn, arguments );
361         };
362 });
363
364 jQuery.extend({
365         clean: function( elems, context, fragment, scripts ) {
366                 context = context || document;
367
368                 // !context.createElement fails in IE with an error but returns typeof 'object'
369                 if ( typeof context.createElement === "undefined" ) {
370                         context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
371                 }
372
373                 var ret = [];
374
375                 jQuery.each(elems, function(i, elem){
376                         if ( typeof elem === "number" ) {
377                                 elem += '';
378                         }
379
380                         if ( !elem ) { return; }
381
382                         // Convert html string into DOM nodes
383                         if ( typeof elem === "string" && !rhtml.test( elem ) ) {
384                                 elem = context.createTextNode( elem );
385
386                         } else if ( typeof elem === "string" ) {
387                                 // Fix "XHTML"-style tags in all browsers
388                                 elem = elem.replace(rxhtmlTag, fcloseTag);
389
390                                 // Trim whitespace, otherwise indexOf won't work as expected
391                                 var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
392                                         wrap = wrapMap[ tag ] || wrapMap._default,
393                                         depth = wrap[0],
394                                         div = context.createElement("div");
395
396                                 // Go to html and back, then peel off extra wrappers
397                                 div.innerHTML = wrap[1] + elem + wrap[2];
398
399                                 // Move to the right depth
400                                 while ( depth-- ) {
401                                         div = div.lastChild;
402                                 }
403
404                                 // Remove IE's autoinserted <tbody> from table fragments
405                                 if ( !jQuery.support.tbody ) {
406
407                                         // String was a <table>, *may* have spurious <tbody>
408                                         var hasBody = rtbody.test(elem),
409                                                 tbody = tag === "table" && !hasBody ?
410                                                         div.firstChild && div.firstChild.childNodes :
411
412                                                         // String was a bare <thead> or <tfoot>
413                                                         wrap[1] == "<table>" && !hasBody ?
414                                                                 div.childNodes :
415                                                                 [];
416
417                                         for ( var j = tbody.length - 1; j >= 0 ; --j ) {
418                                                 if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
419                                                         tbody[ j ].parentNode.removeChild( tbody[ j ] );
420                                                 }
421                                         }
422
423                                 }
424
425                                 // IE completely kills leading whitespace when innerHTML is used
426                                 if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
427                                         div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
428                                 }
429
430                                 elem = jQuery.makeArray( div.childNodes );
431                         }
432
433                         if ( elem.nodeType ) {
434                                 ret.push( elem );
435                         } else {
436                                 ret = jQuery.merge( ret, elem );
437                         }
438
439                 });
440
441                 if ( fragment ) {
442                         for ( var i = 0; ret[i]; i++ ) {
443                                 if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
444                                         scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
445                                 } else {
446                                         if ( ret[i].nodeType === 1 ) {
447                                                 ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
448                                         }
449                                         fragment.appendChild( ret[i] );
450                                 }
451                         }
452                 }
453
454                 return ret;
455         }
456 });
457
458 function cleanData( elems ) {
459         for ( var i = 0, elem, id; (elem = elems[i]) != null; i++ ) {
460                 if ( !jQuery.noData[elem.nodeName.toLowerCase()] && (id = elem[expando]) ) {
461                         delete jQuery.cache[ id ];
462                 }
463         }
464 }