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