Make sure that we don't try to use a detached node (that was in a fragment) as a...
[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         rnocache = /<script|<object|<embed|<option/i,
9         rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,  // checked="checked" or checked (html5)
10         fcloseTag = function( all, front, tag ) {
11                 return rselfClosing.test( tag ) ?
12                         all :
13                         front + "></" + tag + ">";
14         },
15         wrapMap = {
16                 option: [ 1, "<select multiple='multiple'>", "</select>" ],
17                 legend: [ 1, "<fieldset>", "</fieldset>" ],
18                 thead: [ 1, "<table>", "</table>" ],
19                 tr: [ 2, "<table><tbody>", "</tbody></table>" ],
20                 td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
21                 col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
22                 area: [ 1, "<map>", "</map>" ],
23                 _default: [ 0, "", "" ]
24         };
25
26 wrapMap.optgroup = wrapMap.option;
27 wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
28 wrapMap.th = wrapMap.td;
29
30 // IE can't serialize <link> and <script> tags normally
31 if ( !jQuery.support.htmlSerialize ) {
32         wrapMap._default = [ 1, "div<div>", "</div>" ];
33 }
34
35 jQuery.fn.extend({
36         text: function( text ) {
37                 if ( jQuery.isFunction(text) ) {
38                         return this.each(function(i) {
39                                 var self = jQuery(this);
40                                 self.text( text.call(this, i, self.text()) );
41                         });
42                 }
43
44                 if ( typeof text !== "object" && text !== undefined ) {
45                         return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
46                 }
47
48                 return jQuery.text( this );
49         },
50
51         wrapAll: function( html ) {
52                 if ( jQuery.isFunction( html ) ) {
53                         return this.each(function(i) {
54                                 jQuery(this).wrapAll( html.call(this, i) );
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(true);
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                 if ( jQuery.isFunction( html ) ) {
82                         return this.each(function(i) {
83                                 jQuery(this).wrapInner( html.call(this, i) );
84                         });
85                 }
86
87                 return this.each(function() {
88                         var self = jQuery( this ), contents = self.contents();
89
90                         if ( contents.length ) {
91                                 contents.wrapAll( html );
92
93                         } else {
94                                 self.append( html );
95                         }
96                 });
97         },
98
99         wrap: function( html ) {
100                 return this.each(function() {
101                         jQuery( this ).wrapAll( html );
102                 });
103         },
104
105         unwrap: function() {
106                 return this.parent().each(function() {
107                         if ( !jQuery.nodeName( this, "body" ) ) {
108                                 jQuery( this ).replaceWith( this.childNodes );
109                         }
110                 }).end();
111         },
112
113         append: function() {
114                 return this.domManip(arguments, true, function( elem ) {
115                         if ( this.nodeType === 1 ) {
116                                 this.appendChild( elem );
117                         }
118                 });
119         },
120
121         prepend: function() {
122                 return this.domManip(arguments, true, function( elem ) {
123                         if ( this.nodeType === 1 ) {
124                                 this.insertBefore( elem, this.firstChild );
125                         }
126                 });
127         },
128
129         before: function() {
130                 if ( this[0] && this[0].parentNode ) {
131                         return this.domManip(arguments, false, function( elem ) {
132                                 this.parentNode.insertBefore( elem, this );
133                         });
134                 } else if ( arguments.length ) {
135                         var set = jQuery(arguments[0]);
136                         set.push.apply( set, this.toArray() );
137                         return this.pushStack( set, "before", arguments );
138                 }
139         },
140
141         after: function() {
142                 if ( this[0] && this[0].parentNode ) {
143                         return this.domManip(arguments, false, function( elem ) {
144                                 this.parentNode.insertBefore( elem, this.nextSibling );
145                         });
146                 } else if ( arguments.length ) {
147                         var set = this.pushStack( this, "after", arguments );
148                         set.push.apply( set, jQuery(arguments[0]).toArray() );
149                         return set;
150                 }
151         },
152         
153         // keepData is for internal use only--do not document
154         remove: function( selector, keepData ) {
155                 for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
156                         if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
157                                 if ( !keepData && elem.nodeType === 1 ) {
158                                         jQuery.cleanData( elem.getElementsByTagName("*") );
159                                         jQuery.cleanData( [ elem ] );
160                                 }
161
162                                 if ( elem.parentNode ) {
163                                          elem.parentNode.removeChild( elem );
164                                 }
165                         }
166                 }
167                 
168                 return this;
169         },
170
171         empty: function() {
172                 for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
173                         // Remove element nodes and prevent memory leaks
174                         if ( elem.nodeType === 1 ) {
175                                 jQuery.cleanData( elem.getElementsByTagName("*") );
176                         }
177
178                         // Remove any remaining nodes
179                         while ( elem.firstChild ) {
180                                 elem.removeChild( elem.firstChild );
181                         }
182                 }
183                 
184                 return this;
185         },
186
187         clone: function( events ) {
188                 // Do the clone
189                 var ret = this.map(function() {
190                         if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
191                                 // IE copies events bound via attachEvent when
192                                 // using cloneNode. Calling detachEvent on the
193                                 // clone will also remove the events from the orignal
194                                 // In order to get around this, we use innerHTML.
195                                 // Unfortunately, this means some modifications to
196                                 // attributes in IE that are actually only stored
197                                 // as properties will not be copied (such as the
198                                 // the name attribute on an input).
199                                 var html = this.outerHTML, ownerDocument = this.ownerDocument;
200                                 if ( !html ) {
201                                         var div = ownerDocument.createElement("div");
202                                         div.appendChild( this.cloneNode(true) );
203                                         html = div.innerHTML;
204                                 }
205
206                                 return jQuery.clean([html.replace(rinlinejQuery, "")
207                                         // Handle the case in IE 8 where action=/test/> self-closes a tag
208                                         .replace(/=([^="'>\s]+\/)>/g, '="$1">')
209                                         .replace(rleadingWhitespace, "")], ownerDocument)[0];
210                         } else {
211                                 return this.cloneNode(true);
212                         }
213                 });
214
215                 // Copy the events from the original to the clone
216                 if ( events === true ) {
217                         cloneCopyEvent( this, ret );
218                         cloneCopyEvent( this.find("*"), ret.find("*") );
219                 }
220
221                 // Return the cloned set
222                 return ret;
223         },
224
225         html: function( value ) {
226                 if ( value === undefined ) {
227                         return this[0] && this[0].nodeType === 1 ?
228                                 this[0].innerHTML.replace(rinlinejQuery, "") :
229                                 null;
230
231                 // See if we can take a shortcut and just use innerHTML
232                 } else if ( typeof value === "string" && !rnocache.test( value ) &&
233                         (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
234                         !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
235
236                         value = value.replace(rxhtmlTag, fcloseTag);
237
238                         try {
239                                 for ( var i = 0, l = this.length; i < l; i++ ) {
240                                         // Remove element nodes and prevent memory leaks
241                                         if ( this[i].nodeType === 1 ) {
242                                                 jQuery.cleanData( this[i].getElementsByTagName("*") );
243                                                 this[i].innerHTML = value;
244                                         }
245                                 }
246
247                         // If using innerHTML throws an exception, use the fallback method
248                         } catch(e) {
249                                 this.empty().append( value );
250                         }
251
252                 } else if ( jQuery.isFunction( value ) ) {
253                         this.each(function(i){
254                                 var self = jQuery(this), old = self.html();
255                                 self.empty().append(function(){
256                                         return value.call( this, i, old );
257                                 });
258                         });
259
260                 } else {
261                         this.empty().append( value );
262                 }
263
264                 return this;
265         },
266
267         replaceWith: function( value ) {
268                 if ( this[0] && this[0].parentNode ) {
269                         // Make sure that the elements are removed from the DOM before they are inserted
270                         // this can help fix replacing a parent with child elements
271                         if ( jQuery.isFunction( value ) ) {
272                                 return this.each(function(i) {
273                                         var self = jQuery(this), old = self.html();
274                                         self.replaceWith( value.call( this, i, old ) );
275                                 });
276                         }
277
278                         if ( typeof value !== "string" ) {
279                                 value = jQuery(value).detach();
280                         }
281
282                         return this.each(function() {
283                                 var next = this.nextSibling, parent = this.parentNode;
284
285                                 jQuery(this).remove();
286
287                                 if ( next ) {
288                                         jQuery(next).before( value );
289                                 } else {
290                                         jQuery(parent).append( value );
291                                 }
292                         });
293                 } else {
294                         return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
295                 }
296         },
297
298         detach: function( selector ) {
299                 return this.remove( selector, true );
300         },
301
302         domManip: function( args, table, callback ) {
303                 var results, first, value = args[0], scripts = [], fragment, parent;
304
305                 // We can't cloneNode fragments that contain checked, in WebKit
306                 if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
307                         return this.each(function() {
308                                 jQuery(this).domManip( args, table, callback, true );
309                         });
310                 }
311
312                 if ( jQuery.isFunction(value) ) {
313                         return this.each(function(i) {
314                                 var self = jQuery(this);
315                                 args[0] = value.call(this, i, table ? self.html() : undefined);
316                                 self.domManip( args, table, callback );
317                         });
318                 }
319
320                 if ( this[0] ) {
321                         parent = value && value.parentNode;
322
323                         // If we're in a fragment, just use that instead of building a new one
324                         if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
325                                 results = { fragment: parent };
326
327                         } else {
328                                 results = buildFragment( args, this, scripts );
329                         }
330                         
331                         fragment = results.fragment;
332                         
333                         if ( fragment.childNodes.length === 1 ) {
334                                 first = fragment = fragment.firstChild;
335                         } else {
336                                 first = fragment.firstChild;
337                         }
338
339                         if ( first ) {
340                                 table = table && jQuery.nodeName( first, "tr" );
341
342                                 for ( var i = 0, l = this.length; i < l; i++ ) {
343                                         callback.call(
344                                                 table ?
345                                                         root(this[i], first) :
346                                                         this[i],
347                                                 i > 0 || results.cacheable || this.length > 1  ?
348                                                         fragment.cloneNode(true) :
349                                                         fragment
350                                         );
351                                 }
352                         }
353
354                         if ( scripts.length ) {
355                                 jQuery.each( scripts, evalScript );
356                         }
357                 }
358
359                 return this;
360
361                 function root( elem, cur ) {
362                         return jQuery.nodeName(elem, "table") ?
363                                 (elem.getElementsByTagName("tbody")[0] ||
364                                 elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
365                                 elem;
366                 }
367         }
368 });
369
370 function cloneCopyEvent(orig, ret) {
371         var i = 0;
372
373         ret.each(function() {
374                 if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) {
375                         return;
376                 }
377
378                 var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events;
379
380                 if ( events ) {
381                         delete curData.handle;
382                         curData.events = {};
383
384                         for ( var type in events ) {
385                                 for ( var handler in events[ type ] ) {
386                                         jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
387                                 }
388                         }
389                 }
390         });
391 }
392
393 function buildFragment( args, nodes, scripts ) {
394         var fragment, cacheable, cacheresults,
395                 doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
396
397         // Only cache "small" (1/2 KB) strings that are associated with the main document
398         // Cloning options loses the selected state, so don't cache them
399         // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
400         // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
401         if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
402                 !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
403
404                 cacheable = true;
405                 cacheresults = jQuery.fragments[ args[0] ];
406                 if ( cacheresults ) {
407                         if ( cacheresults !== 1 ) {
408                                 fragment = cacheresults;
409                         }
410                 }
411         }
412
413         if ( !fragment ) {
414                 fragment = doc.createDocumentFragment();
415                 jQuery.clean( args, doc, fragment, scripts );
416         }
417
418         if ( cacheable ) {
419                 jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
420         }
421
422         return { fragment: fragment, cacheable: cacheable };
423 }
424
425 jQuery.fragments = {};
426
427 jQuery.each({
428         appendTo: "append",
429         prependTo: "prepend",
430         insertBefore: "before",
431         insertAfter: "after",
432         replaceAll: "replaceWith"
433 }, function( name, original ) {
434         jQuery.fn[ name ] = function( selector ) {
435                 var ret = [], insert = jQuery( selector ),
436                         parent = this.length === 1 && this[0].parentNode;
437                 
438                 if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
439                         insert[ original ]( this[0] );
440                         return this;
441                         
442                 } else {
443                         for ( var i = 0, l = insert.length; i < l; i++ ) {
444                                 var elems = (i > 0 ? this.clone(true) : this).get();
445                                 jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
446                                 ret = ret.concat( elems );
447                         }
448                 
449                         return this.pushStack( ret, name, insert.selector );
450                 }
451         };
452 });
453
454 jQuery.extend({
455         clean: function( elems, context, fragment, scripts ) {
456                 context = context || document;
457
458                 // !context.createElement fails in IE with an error but returns typeof 'object'
459                 if ( typeof context.createElement === "undefined" ) {
460                         context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
461                 }
462
463                 var ret = [];
464
465                 for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
466                         if ( typeof elem === "number" ) {
467                                 elem += "";
468                         }
469
470                         if ( !elem ) {
471                                 continue;
472                         }
473
474                         // Convert html string into DOM nodes
475                         if ( typeof elem === "string" && !rhtml.test( elem ) ) {
476                                 elem = context.createTextNode( elem );
477
478                         } else if ( typeof elem === "string" ) {
479                                 // Fix "XHTML"-style tags in all browsers
480                                 elem = elem.replace(rxhtmlTag, fcloseTag);
481
482                                 // Trim whitespace, otherwise indexOf won't work as expected
483                                 var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
484                                         wrap = wrapMap[ tag ] || wrapMap._default,
485                                         depth = wrap[0],
486                                         div = context.createElement("div");
487
488                                 // Go to html and back, then peel off extra wrappers
489                                 div.innerHTML = wrap[1] + elem + wrap[2];
490
491                                 // Move to the right depth
492                                 while ( depth-- ) {
493                                         div = div.lastChild;
494                                 }
495
496                                 // Remove IE's autoinserted <tbody> from table fragments
497                                 if ( !jQuery.support.tbody ) {
498
499                                         // String was a <table>, *may* have spurious <tbody>
500                                         var hasBody = rtbody.test(elem),
501                                                 tbody = tag === "table" && !hasBody ?
502                                                         div.firstChild && div.firstChild.childNodes :
503
504                                                         // String was a bare <thead> or <tfoot>
505                                                         wrap[1] === "<table>" && !hasBody ?
506                                                                 div.childNodes :
507                                                                 [];
508
509                                         for ( var j = tbody.length - 1; j >= 0 ; --j ) {
510                                                 if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
511                                                         tbody[ j ].parentNode.removeChild( tbody[ j ] );
512                                                 }
513                                         }
514
515                                 }
516
517                                 // IE completely kills leading whitespace when innerHTML is used
518                                 if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
519                                         div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
520                                 }
521
522                                 elem = div.childNodes;
523                         }
524
525                         if ( elem.nodeType ) {
526                                 ret.push( elem );
527                         } else {
528                                 ret = jQuery.merge( ret, elem );
529                         }
530                 }
531
532                 if ( fragment ) {
533                         for ( var i = 0; ret[i]; i++ ) {
534                                 if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
535                                         scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
536                                 
537                                 } else {
538                                         if ( ret[i].nodeType === 1 ) {
539                                                 ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
540                                         }
541                                         fragment.appendChild( ret[i] );
542                                 }
543                         }
544                 }
545
546                 return ret;
547         },
548         
549         cleanData: function( elems ) {
550                 var data, id, cache = jQuery.cache;
551                 
552                 for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
553                         id = elem[ jQuery.expando ];
554                         
555                         if ( id ) {
556                                 data = cache[ id ];
557                                 
558                                 if ( data.events ) {
559                                         for ( var event in data.events ) {
560                                                 removeEvent( elem, event, data.handle );
561                                         }
562                                 }
563                                 
564                                 removeExpando( elem );
565                                 
566                                 delete cache[ id ];
567                         }
568                 }
569         }
570 });