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