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