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