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