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