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