Adding some fixes for commit [6537]. If there's leading whitespace, or if an exceptio...
[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                         (!jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
193                         !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
194
195                         try {
196                                 for ( var i = 0, l = this.length; i < l; i++ ) {
197                                         // Remove element nodes and prevent memory leaks
198                                         if ( this[i].nodeType === 1 ) {
199                                                 cleanData( this[i].getElementsByTagName("*") );
200                                                 this[i].innerHTML = value;
201                                         }
202                                 }
203
204                         // If using innerHTML throws an exception, use the fallback method
205                         } catch(e) {
206                                 this.empty().append( value );
207                         }
208
209                 } else {
210                         this.empty().append( value );
211                 }
212
213                 return this;
214         },
215
216         replaceWith: function( value ) {
217                 if ( this[0] && this[0].parentNode ) {
218                         return this.after( value ).remove();
219                 } else {
220                         return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
221                 }
222         },
223
224         detach: function( selector ) {
225                 return this.remove( selector, true );
226         },
227
228         domManip: function( args, table, callback ) {
229                 var results, first, value = args[0], scripts = [];
230
231                 if ( jQuery.isFunction(value) ) {
232                         return this.each(function() {
233                                 args[0] = value.call(this);
234                                 return jQuery(this).domManip( args, table, callback );
235                         });
236                 }
237
238                 if ( this[0] ) {
239                         // If we're in a fragment, just use that instead of building a new one
240                         if ( args[0] && args[0].parentNode && args[0].parentNode.nodeType === 11 ) {
241                                 results = { fragment: args[0].parentNode };
242                         } else {
243                                 results = buildFragment( args, this, scripts );
244                         }
245
246                         first = results.fragment.firstChild;
247
248                         if ( first ) {
249                                 table = table && jQuery.nodeName( first, "tr" );
250
251                                 for ( var i = 0, l = this.length; i < l; i++ ) {
252                                         callback.call(
253                                                 table ?
254                                                         root(this[i], first) :
255                                                         this[i],
256                                                 results.cacheable || this.length > 1 || i > 0 ?
257                                                         results.fragment.cloneNode(true) :
258                                                         results.fragment
259                                         );
260                                 }
261                         }
262
263                         if ( scripts ) {
264                                 jQuery.each( scripts, evalScript );
265                         }
266                 }
267
268                 return this;
269
270                 function root( elem, cur ) {
271                         return jQuery.nodeName(elem, "table") ?
272                                 (elem.getElementsByTagName("tbody")[0] ||
273                                 elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
274                                 elem;
275                 }
276         }
277 });
278
279 function buildFragment(args, nodes, scripts){
280         var fragment, cacheable, cached, cacheresults, doc;
281
282         if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && args[0].indexOf("<option") < 0 ) {
283                 cacheable = true;
284                 cacheresults = jQuery.fragments[ args[0] ];
285                 if ( cacheresults ) {
286                         if ( cacheresults !== 1 ) {
287                                 fragment = cacheresults;
288                         }
289                         cached = true;
290                 }
291         }
292
293         if ( !fragment ) {
294                 doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
295                 fragment = doc.createDocumentFragment();
296                 jQuery.clean( args, doc, fragment, scripts );
297         }
298
299         if ( cacheable ) {
300                 jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
301         }
302
303         return { fragment: fragment, cacheable: cacheable };
304 }
305
306 jQuery.fragments = {};
307
308 jQuery.each({
309         appendTo: "append",
310         prependTo: "prepend",
311         insertBefore: "before",
312         insertAfter: "after",
313         replaceAll: "replaceWith"
314 }, function(name, original){
315         jQuery.fn[ name ] = function( selector ) {
316                 var ret = [], insert = jQuery( selector );
317
318                 for ( var i = 0, l = insert.length; i < l; i++ ) {
319                         var elems = (i > 0 ? this.clone(true) : this).get();
320                         jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
321                         ret = ret.concat( elems );
322                 }
323                 return this.pushStack( ret, name, insert.selector );
324         };
325 });
326
327 jQuery.each({
328         // keepData is for internal use only--do not document
329         remove: function( selector, keepData ) {
330                 if ( !selector || jQuery.multiFilter( selector, [ this ] ).length ) {
331                         if ( !keepData && this.nodeType === 1 ) {
332                                 cleanData( this.getElementsByTagName("*") );
333                                 cleanData( [ this ] );
334                         }
335
336                         if ( this.parentNode ) {
337                                  this.parentNode.removeChild( this );
338                         }
339                 }
340         },
341
342         empty: function() {
343                 // Remove element nodes and prevent memory leaks
344                 if ( this.nodeType === 1 ) {
345                         cleanData( this.getElementsByTagName("*") );
346                 }
347
348                 // Remove any remaining nodes
349                 while ( this.firstChild ) {
350                         this.removeChild( this.firstChild );
351                 }
352         }
353 }, function(name, fn){
354         jQuery.fn[ name ] = function(){
355                 return this.each( fn, arguments );
356         };
357 });
358
359 jQuery.extend({
360         clean: function( elems, context, fragment, scripts ) {
361                 context = context || document;
362
363                 // !context.createElement fails in IE with an error but returns typeof 'object'
364                 if ( typeof context.createElement === "undefined" ) {
365                         context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
366                 }
367
368                 var ret = [], div = context.createElement("div");
369
370                 jQuery.each(elems, function(i, elem){
371                         if ( typeof elem === "number" ) {
372                                 elem += '';
373                         }
374
375                         if ( !elem ) { return; }
376
377                         // Convert html string into DOM nodes
378                         if ( typeof elem === "string" && !rhtml.test( elem ) ) {
379                                 elem = context.createTextNode( elem );
380
381                         } else if ( typeof elem === "string" ) {
382                                 // Fix "XHTML"-style tags in all browsers
383                                 elem = elem.replace(rxhtmlTag, fcloseTag);
384
385                                 // Trim whitespace, otherwise indexOf won't work as expected
386                                 var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
387                                         wrap = wrapMap[ tag ] || wrapMap._default,
388                                         depth = wrap[0];
389
390                                 // Go to html and back, then peel off extra wrappers
391                                 div.innerHTML = wrap[1] + elem + wrap[2];
392
393                                 // Move to the right depth
394                                 while ( depth-- ) {
395                                         div = div.lastChild;
396                                 }
397
398                                 // Remove IE's autoinserted <tbody> from table fragments
399                                 if ( !jQuery.support.tbody ) {
400
401                                         // String was a <table>, *may* have spurious <tbody>
402                                         var hasBody = rtbody.test(elem),
403                                                 tbody = tag === "table" && !hasBody ?
404                                                         div.firstChild && div.firstChild.childNodes :
405
406                                                         // String was a bare <thead> or <tfoot>
407                                                         wrap[1] == "<table>" && !hasBody ?
408                                                                 div.childNodes :
409                                                                 [];
410
411                                         for ( var j = tbody.length - 1; j >= 0 ; --j ) {
412                                                 if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
413                                                         tbody[ j ].parentNode.removeChild( tbody[ j ] );
414                                                 }
415                                         }
416
417                                 }
418
419                                 // IE completely kills leading whitespace when innerHTML is used
420                                 if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
421                                         div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
422                                 }
423
424                                 elem = jQuery.makeArray( div.childNodes );
425                         }
426
427                         if ( elem.nodeType ) {
428                                 ret.push( elem );
429                         } else {
430                                 ret = jQuery.merge( ret, elem );
431                         }
432
433                 });
434
435                 if ( fragment ) {
436                         for ( var i = 0; ret[i]; i++ ) {
437                                 if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
438                                         scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
439                                 } else {
440                                         if ( ret[i].nodeType === 1 ) {
441                                                 ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
442                                         }
443                                         fragment.appendChild( ret[i] );
444                                 }
445                         }
446                 }
447
448                 return ret;
449         }
450 });
451
452 function cleanData( elems ) {
453         for ( var i = 0, elem, id; (elem = elems[i]) != null; i++ ) {
454                 if ( (id = elem[expando]) ) {
455                         delete jQuery.cache[ id ];
456                 }
457         }
458 }