A follow-up to [6578] (which stopped adding expandos to elements that didn't have...
[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 if ( arguments.length ) {
115                         var set = jQuery(arguments[0]);
116                         set.push.apply( set, this.toArray() );
117                         return this.pushStack( set, "before", arguments );
118                 }
119         },
120
121         after: function() {
122                 if ( this[0] && this[0].parentNode ) {
123                         return this.domManip(arguments, false, function(elem){
124                                 this.parentNode.insertBefore( elem, this.nextSibling );
125                         });
126                 } else if ( arguments.length ) {
127                         var set = this.pushStack( this, "after", arguments );
128                         set.push.apply( set, jQuery(arguments[0]).toArray() );
129                         return set;
130                 }
131         },
132
133         clone: function( events ) {
134                 // Do the clone
135                 var ret = this.map(function(){
136                         if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
137                                 // IE copies events bound via attachEvent when
138                                 // using cloneNode. Calling detachEvent on the
139                                 // clone will also remove the events from the orignal
140                                 // In order to get around this, we use innerHTML.
141                                 // Unfortunately, this means some modifications to
142                                 // attributes in IE that are actually only stored
143                                 // as properties will not be copied (such as the
144                                 // the name attribute on an input).
145                                 var html = this.outerHTML, ownerDocument = this.ownerDocument;
146                                 if ( !html ) {
147                                         var div = ownerDocument.createElement("div");
148                                         div.appendChild( this.cloneNode(true) );
149                                         html = div.innerHTML;
150                                 }
151
152                                 return jQuery.clean([html.replace(rinlinejQuery, "")
153                                         .replace(rleadingWhitespace, "")], ownerDocument)[0];
154                         } else {
155                                 return this.cloneNode(true);
156                         }
157                 });
158
159                 // Copy the events from the original to the clone
160                 if ( events === true ) {
161                         var orig = this.find("*").andSelf(), i = 0;
162
163                         ret.find("*").andSelf().each(function(){
164                                 if ( this.nodeName !== orig[i].nodeName ) { return; }
165
166                                 var events = jQuery.data( orig[i], "events" );
167
168                                 for ( var type in events ) {
169                                         for ( var handler in events[ type ] ) {
170                                                 jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
171                                         }
172                                 }
173
174                                 i++;
175                         });
176                 }
177
178                 // Return the cloned set
179                 return ret;
180         },
181
182         html: function( value ) {
183                 if ( value === undefined ) {
184                         return this[0] ?
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                         try {
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                                                 this[i].innerHTML = value;
199                                         }
200                                 }
201
202                         // If using innerHTML throws an exception, use the fallback method
203                         } catch(e) {
204                                 this.empty().append( value );
205                         }
206
207                 } else {
208                         this.empty().append( value );
209                 }
210
211                 return this;
212         },
213
214         replaceWith: function( value ) {
215                 if ( this[0] && this[0].parentNode ) {
216                         return this.after( value ).remove();
217                 } else {
218                         return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
219                 }
220         },
221
222         detach: function( selector ) {
223                 return this.remove( selector, true );
224         },
225
226         domManip: function( args, table, callback ) {
227                 var results, first, value = args[0], scripts = [];
228
229                 if ( jQuery.isFunction(value) ) {
230                         return this.each(function() {
231                                 args[0] = value.call(this);
232                                 return jQuery(this).domManip( args, table, callback );
233                         });
234                 }
235
236                 if ( this[0] ) {
237                         // If we're in a fragment, just use that instead of building a new one
238                         if ( args[0] && args[0].parentNode && args[0].parentNode.nodeType === 11 ) {
239                                 results = { fragment: args[0].parentNode };
240                         } else {
241                                 results = buildFragment( args, this, scripts );
242                         }
243
244                         first = results.fragment.firstChild;
245
246                         if ( first ) {
247                                 table = table && jQuery.nodeName( first, "tr" );
248
249                                 for ( var i = 0, l = this.length; i < l; i++ ) {
250                                         callback.call(
251                                                 table ?
252                                                         root(this[i], first) :
253                                                         this[i],
254                                                 results.cacheable || this.length > 1 || i > 0 ?
255                                                         results.fragment.cloneNode(true) :
256                                                         results.fragment
257                                         );
258                                 }
259                         }
260
261                         if ( scripts ) {
262                                 jQuery.each( scripts, evalScript );
263                         }
264                 }
265
266                 return this;
267
268                 function root( elem, cur ) {
269                         return jQuery.nodeName(elem, "table") ?
270                                 (elem.getElementsByTagName("tbody")[0] ||
271                                 elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
272                                 elem;
273                 }
274         }
275 });
276
277 function buildFragment(args, nodes, scripts){
278         var fragment, cacheable, cached, cacheresults, doc;
279
280         if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && args[0].indexOf("<option") < 0 ) {
281                 cacheable = true;
282                 cacheresults = jQuery.fragments[ args[0] ];
283                 if ( cacheresults ) {
284                         if ( cacheresults !== 1 ) {
285                                 fragment = cacheresults;
286                         }
287                         cached = true;
288                 }
289         }
290
291         if ( !fragment ) {
292                 doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
293                 fragment = doc.createDocumentFragment();
294                 jQuery.clean( args, doc, fragment, scripts );
295         }
296
297         if ( cacheable ) {
298                 jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
299         }
300
301         return { fragment: fragment, cacheable: cacheable };
302 }
303
304 jQuery.fragments = {};
305
306 jQuery.each({
307         appendTo: "append",
308         prependTo: "prepend",
309         insertBefore: "before",
310         insertAfter: "after",
311         replaceAll: "replaceWith"
312 }, function(name, original){
313         jQuery.fn[ name ] = function( selector ) {
314                 var ret = [], insert = jQuery( selector );
315
316                 for ( var i = 0, l = insert.length; i < l; i++ ) {
317                         var elems = (i > 0 ? this.clone(true) : this).get();
318                         jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
319                         ret = ret.concat( elems );
320                 }
321                 return this.pushStack( ret, name, insert.selector );
322         };
323 });
324
325 jQuery.each({
326         // keepData is for internal use only--do not document
327         remove: function( selector, keepData ) {
328                 if ( !selector || jQuery.multiFilter( selector, [ this ] ).length ) {
329                         if ( !keepData && this.nodeType === 1 ) {
330                                 cleanData( this.getElementsByTagName("*") );
331                                 cleanData( [ this ] );
332                         }
333
334                         if ( this.parentNode ) {
335                                  this.parentNode.removeChild( this );
336                         }
337                 }
338         },
339
340         empty: function() {
341                 // Remove element nodes and prevent memory leaks
342                 if ( this.nodeType === 1 ) {
343                         cleanData( this.getElementsByTagName("*") );
344                 }
345
346                 // Remove any remaining nodes
347                 while ( this.firstChild ) {
348                         this.removeChild( this.firstChild );
349                 }
350         }
351 }, function(name, fn){
352         jQuery.fn[ name ] = function(){
353                 return this.each( fn, arguments );
354         };
355 });
356
357 jQuery.extend({
358         clean: function( elems, context, fragment, scripts ) {
359                 context = context || document;
360
361                 // !context.createElement fails in IE with an error but returns typeof 'object'
362                 if ( typeof context.createElement === "undefined" ) {
363                         context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
364                 }
365
366                 var ret = [], div = context.createElement("div");
367
368                 jQuery.each(elems, function(i, elem){
369                         if ( typeof elem === "number" ) {
370                                 elem += '';
371                         }
372
373                         if ( !elem ) { return; }
374
375                         // Convert html string into DOM nodes
376                         if ( typeof elem === "string" && !rhtml.test( elem ) ) {
377                                 elem = context.createTextNode( elem );
378
379                         } else if ( typeof elem === "string" ) {
380                                 // Fix "XHTML"-style tags in all browsers
381                                 elem = elem.replace(rxhtmlTag, fcloseTag);
382
383                                 // Trim whitespace, otherwise indexOf won't work as expected
384                                 var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
385                                         wrap = wrapMap[ tag ] || wrapMap._default,
386                                         depth = wrap[0];
387
388                                 // Go to html and back, then peel off extra wrappers
389                                 div.innerHTML = wrap[1] + elem + wrap[2];
390
391                                 // Move to the right depth
392                                 while ( depth-- ) {
393                                         div = div.lastChild;
394                                 }
395
396                                 // Remove IE's autoinserted <tbody> from table fragments
397                                 if ( !jQuery.support.tbody ) {
398
399                                         // String was a <table>, *may* have spurious <tbody>
400                                         var hasBody = rtbody.test(elem),
401                                                 tbody = tag === "table" && !hasBody ?
402                                                         div.firstChild && div.firstChild.childNodes :
403
404                                                         // String was a bare <thead> or <tfoot>
405                                                         wrap[1] == "<table>" && !hasBody ?
406                                                                 div.childNodes :
407                                                                 [];
408
409                                         for ( var j = tbody.length - 1; j >= 0 ; --j ) {
410                                                 if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
411                                                         tbody[ j ].parentNode.removeChild( tbody[ j ] );
412                                                 }
413                                         }
414
415                                 }
416
417                                 // IE completely kills leading whitespace when innerHTML is used
418                                 if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
419                                         div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
420                                 }
421
422                                 elem = jQuery.makeArray( div.childNodes );
423                         }
424
425                         if ( elem.nodeType ) {
426                                 ret.push( elem );
427                         } else {
428                                 ret = jQuery.merge( ret, elem );
429                         }
430
431                 });
432
433                 if ( fragment ) {
434                         for ( var i = 0; ret[i]; i++ ) {
435                                 if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
436                                         scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
437                                 } else {
438                                         if ( ret[i].nodeType === 1 ) {
439                                                 ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
440                                         }
441                                         fragment.appendChild( ret[i] );
442                                 }
443                         }
444                 }
445
446                 return ret;
447         }
448 });
449
450 function cleanData( elems ) {
451         for ( var i = 0, elem, id; (elem = elems[i]) != null; i++ ) {
452                 if ( (id = elem[expando]) ) {
453                         delete jQuery.cache[ id ];
454                 }
455         }
456 }