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