Make sure that the correct context is being passed in for replaceWith(fn). Fixes...
[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         rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,  // checked="checked" or checked (html5)
9         fcloseTag = function( all, front, tag ) {
10                 return rselfClosing.test( tag ) ?
11                         all :
12                         front + "></" + tag + ">";
13         },
14         wrapMap = {
15                 option: [ 1, "<select multiple='multiple'>", "</select>" ],
16                 legend: [ 1, "<fieldset>", "</fieldset>" ],
17                 thead: [ 1, "<table>", "</table>" ],
18                 tr: [ 2, "<table><tbody>", "</tbody></table>" ],
19                 td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
20                 col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
21                 area: [ 1, "<map>", "</map>" ],
22                 _default: [ 0, "", "" ]
23         };
24
25 wrapMap.optgroup = wrapMap.option;
26 wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
27 wrapMap.th = wrapMap.td;
28
29 // IE can't serialize <link> and <script> tags normally
30 if ( !jQuery.support.htmlSerialize ) {
31         wrapMap._default = [ 1, "div<div>", "</div>" ];
32 }
33
34 jQuery.fn.extend({
35         text: function( text ) {
36                 if ( jQuery.isFunction(text) ) {
37                         return this.each(function(i) {
38                                 var self = jQuery(this);
39                                 self.text( text.call(this, i, self.text()) );
40                         });
41                 }
42
43                 if ( typeof text !== "object" && text !== undefined ) {
44                         return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
45                 }
46
47                 return jQuery.getText( this );
48         },
49
50         wrapAll: function( html ) {
51                 if ( jQuery.isFunction( html ) ) {
52                         return this.each(function(i) {
53                                 jQuery(this).wrapAll( html.call(this, i) );
54                         });
55                 }
56
57                 if ( this[0] ) {
58                         // The elements to wrap the target around
59                         var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
60
61                         if ( this[0].parentNode ) {
62                                 wrap.insertBefore( this[0] );
63                         }
64
65                         wrap.map(function() {
66                                 var elem = this;
67
68                                 while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
69                                         elem = elem.firstChild;
70                                 }
71
72                                 return elem;
73                         }).append(this);
74                 }
75
76                 return this;
77         },
78
79         wrapInner: function( html ) {
80                 if ( jQuery.isFunction( html ) ) {
81                         return this.each(function(i) {
82                                 jQuery(this).wrapInner( html.call(this, i) );
83                         });
84                 }
85
86                 return this.each(function() {
87                         var self = jQuery( this ), 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         clone: function( events ) {
153                 // Do the clone
154                 var ret = this.map(function() {
155                         if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
156                                 // IE copies events bound via attachEvent when
157                                 // using cloneNode. Calling detachEvent on the
158                                 // clone will also remove the events from the orignal
159                                 // In order to get around this, we use innerHTML.
160                                 // Unfortunately, this means some modifications to
161                                 // attributes in IE that are actually only stored
162                                 // as properties will not be copied (such as the
163                                 // the name attribute on an input).
164                                 var html = this.outerHTML, ownerDocument = this.ownerDocument;
165                                 if ( !html ) {
166                                         var div = ownerDocument.createElement("div");
167                                         div.appendChild( this.cloneNode(true) );
168                                         html = div.innerHTML;
169                                 }
170
171                                 return jQuery.clean([html.replace(rinlinejQuery, "")
172                                         .replace(rleadingWhitespace, "")], ownerDocument)[0];
173                         } else {
174                                 return this.cloneNode(true);
175                         }
176                 });
177
178                 // Copy the events from the original to the clone
179                 if ( events === true ) {
180                         cloneCopyEvent( this, ret );
181                         cloneCopyEvent( this.find("*"), ret.find("*") );
182                 }
183
184                 // Return the cloned set
185                 return ret;
186         },
187
188         html: function( value ) {
189                 if ( value === undefined ) {
190                         return this[0] && this[0].nodeType === 1 ?
191                                 this[0].innerHTML.replace(rinlinejQuery, "") :
192                                 null;
193
194                 // See if we can take a shortcut and just use innerHTML
195                 } else if ( typeof value === "string" && !/<script/i.test( value ) &&
196                         (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
197                         !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
198
199                         value = value.replace(rxhtmlTag, fcloseTag);
200
201                         try {
202                                 for ( var i = 0, l = this.length; i < l; i++ ) {
203                                         // Remove element nodes and prevent memory leaks
204                                         if ( this[i].nodeType === 1 ) {
205                                                 jQuery.cleanData( this[i].getElementsByTagName("*") );
206                                                 this[i].innerHTML = value;
207                                         }
208                                 }
209
210                         // If using innerHTML throws an exception, use the fallback method
211                         } catch(e) {
212                                 this.empty().append( value );
213                         }
214
215                 } else if ( jQuery.isFunction( value ) ) {
216                         this.each(function(i){
217                                 var self = jQuery(this), old = self.html();
218                                 self.empty().append(function(){
219                                         return value.call( this, i, old );
220                                 });
221                         });
222
223                 } else {
224                         this.empty().append( value );
225                 }
226
227                 return this;
228         },
229
230         replaceWith: function( value ) {
231                 if ( this[0] && this[0].parentNode ) {
232                         // Make sure that the elements are removed from the DOM before they are inserted
233                         // this can help fix replacing a parent with child elements
234                         if ( !jQuery.isFunction( value ) ) {
235                                 value = jQuery( value ).detach();
236
237                         } else {
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                         return this.each(function() {
245                                 var next = this.nextSibling, parent = this.parentNode;
246
247                                 jQuery(this).remove();
248
249                                 if ( next ) {
250                                         jQuery(next).before( value );
251                                 } else {
252                                         jQuery(parent).append( value );
253                                 }
254                         });
255                 } else {
256                         return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
257                 }
258         },
259
260         detach: function( selector ) {
261                 return this.remove( selector, true );
262         },
263
264         domManip: function( args, table, callback ) {
265                 var results, first, value = args[0], scripts = [];
266
267                 // We can't cloneNode fragments that contain checked, in WebKit
268                 if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
269                         return this.each(function() {
270                                 jQuery(this).domManip( args, table, callback, true );
271                         });
272                 }
273
274                 if ( jQuery.isFunction(value) ) {
275                         return this.each(function(i) {
276                                 var self = jQuery(this);
277                                 args[0] = value.call(this, i, table ? self.html() : undefined);
278                                 self.domManip( args, table, callback );
279                         });
280                 }
281
282                 if ( this[0] ) {
283                         // If we're in a fragment, just use that instead of building a new one
284                         if ( args[0] && args[0].parentNode && args[0].parentNode.nodeType === 11 ) {
285                                 results = { fragment: args[0].parentNode };
286                         } else {
287                                 results = buildFragment( args, this, scripts );
288                         }
289
290                         first = results.fragment.firstChild;
291
292                         if ( first ) {
293                                 table = table && jQuery.nodeName( first, "tr" );
294
295                                 for ( var i = 0, l = this.length; i < l; i++ ) {
296                                         callback.call(
297                                                 table ?
298                                                         root(this[i], first) :
299                                                         this[i],
300                                                 results.cacheable || this.length > 1 || i > 0 ?
301                                                         results.fragment.cloneNode(true) :
302                                                         results.fragment
303                                         );
304                                 }
305                         }
306
307                         if ( scripts ) {
308                                 jQuery.each( scripts, evalScript );
309                         }
310                 }
311
312                 return this;
313
314                 function root( elem, cur ) {
315                         return jQuery.nodeName(elem, "table") ?
316                                 (elem.getElementsByTagName("tbody")[0] ||
317                                 elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
318                                 elem;
319                 }
320         }
321 });
322
323 function cloneCopyEvent(orig, ret) {
324         var i = 0;
325
326         ret.each(function() {
327                 if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) {
328                         return;
329                 }
330
331                 var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events;
332
333                 if ( events ) {
334                         delete curData.handle;
335                         curData.events = {};
336
337                         for ( var type in events ) {
338                                 for ( var handler in events[ type ] ) {
339                                         jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
340                                 }
341                         }
342                 }
343         });
344 }
345
346 function buildFragment( args, nodes, scripts ) {
347         var fragment, cacheable, cacheresults, doc;
348
349         // webkit does not clone 'checked' attribute of radio inputs on cloneNode, so don't cache if string has a checked
350         if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && args[0].indexOf("<option") < 0 && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
351                 cacheable = true;
352                 cacheresults = jQuery.fragments[ args[0] ];
353                 if ( cacheresults ) {
354                         if ( cacheresults !== 1 ) {
355                                 fragment = cacheresults;
356                         }
357                 }
358         }
359
360         if ( !fragment ) {
361                 doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
362                 fragment = doc.createDocumentFragment();
363                 jQuery.clean( args, doc, fragment, scripts );
364         }
365
366         if ( cacheable ) {
367                 jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
368         }
369
370         return { fragment: fragment, cacheable: cacheable };
371 }
372
373 jQuery.fragments = {};
374
375 jQuery.each({
376         appendTo: "append",
377         prependTo: "prepend",
378         insertBefore: "before",
379         insertAfter: "after",
380         replaceAll: "replaceWith"
381 }, function( name, original ) {
382         jQuery.fn[ name ] = function( selector ) {
383                 var ret = [], insert = jQuery( selector );
384
385                 for ( var i = 0, l = insert.length; i < l; i++ ) {
386                         var elems = (i > 0 ? this.clone(true) : this).get();
387                         jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
388                         ret = ret.concat( elems );
389                 }
390                 return this.pushStack( ret, name, insert.selector );
391         };
392 });
393
394 jQuery.each({
395         // keepData is for internal use only--do not document
396         remove: function( selector, keepData ) {
397                 if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
398                         if ( !keepData && this.nodeType === 1 ) {
399                                 jQuery.cleanData( this.getElementsByTagName("*") );
400                                 jQuery.cleanData( [ this ] );
401                         }
402
403                         if ( this.parentNode ) {
404                                  this.parentNode.removeChild( this );
405                         }
406                 }
407         },
408
409         empty: function() {
410                 // Remove element nodes and prevent memory leaks
411                 if ( this.nodeType === 1 ) {
412                         jQuery.cleanData( this.getElementsByTagName("*") );
413                 }
414
415                 // Remove any remaining nodes
416                 while ( this.firstChild ) {
417                         this.removeChild( this.firstChild );
418                 }
419         }
420 }, function( name, fn ) {
421         jQuery.fn[ name ] = function() {
422                 return this.each( fn, arguments );
423         };
424 });
425
426 jQuery.extend({
427         clean: function( elems, context, fragment, scripts ) {
428                 context = context || document;
429
430                 // !context.createElement fails in IE with an error but returns typeof 'object'
431                 if ( typeof context.createElement === "undefined" ) {
432                         context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
433                 }
434
435                 var ret = [];
436
437                 jQuery.each(elems, function( i, elem ) {
438                         if ( typeof elem === "number" ) {
439                                 elem += "";
440                         }
441
442                         if ( !elem ) {
443                                 return;
444                         }
445
446                         // Convert html string into DOM nodes
447                         if ( typeof elem === "string" && !rhtml.test( elem ) ) {
448                                 elem = context.createTextNode( elem );
449
450                         } else if ( typeof elem === "string" ) {
451                                 // Fix "XHTML"-style tags in all browsers
452                                 elem = elem.replace(rxhtmlTag, fcloseTag);
453
454                                 // Trim whitespace, otherwise indexOf won't work as expected
455                                 var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
456                                         wrap = wrapMap[ tag ] || wrapMap._default,
457                                         depth = wrap[0],
458                                         div = context.createElement("div");
459
460                                 // Go to html and back, then peel off extra wrappers
461                                 div.innerHTML = wrap[1] + elem + wrap[2];
462
463                                 // Move to the right depth
464                                 while ( depth-- ) {
465                                         div = div.lastChild;
466                                 }
467
468                                 // Remove IE's autoinserted <tbody> from table fragments
469                                 if ( !jQuery.support.tbody ) {
470
471                                         // String was a <table>, *may* have spurious <tbody>
472                                         var hasBody = rtbody.test(elem),
473                                                 tbody = tag === "table" && !hasBody ?
474                                                         div.firstChild && div.firstChild.childNodes :
475
476                                                         // String was a bare <thead> or <tfoot>
477                                                         wrap[1] === "<table>" && !hasBody ?
478                                                                 div.childNodes :
479                                                                 [];
480
481                                         for ( var j = tbody.length - 1; j >= 0 ; --j ) {
482                                                 if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
483                                                         tbody[ j ].parentNode.removeChild( tbody[ j ] );
484                                                 }
485                                         }
486
487                                 }
488
489                                 // IE completely kills leading whitespace when innerHTML is used
490                                 if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
491                                         div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
492                                 }
493
494                                 elem = jQuery.makeArray( div.childNodes );
495                         }
496
497                         if ( elem.nodeType ) {
498                                 ret.push( elem );
499                         } else {
500                                 ret = jQuery.merge( ret, elem );
501                         }
502
503                 });
504
505                 if ( fragment ) {
506                         for ( var i = 0; ret[i]; i++ ) {
507                                 if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
508                                         scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
509                                 } else {
510                                         if ( ret[i].nodeType === 1 ) {
511                                                 ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
512                                         }
513                                         fragment.appendChild( ret[i] );
514                                 }
515                         }
516                 }
517
518                 return ret;
519         },
520         
521         cleanData: function( elems ) {
522                 for ( var i = 0, elem, id; (elem = elems[i]) != null; i++ ) {
523                         jQuery.event.remove( elem );
524                         jQuery.removeData( elem );
525                 }
526         }
527 });