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