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