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