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