We don't do end of line comments, move them above.
[jquery.git] / src / manipulation.js
1 (function( jQuery ) {
2
3 var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
4         rleadingWhitespace = /^\s+/,
5         rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
6         rtagName = /<([\w:]+)/,
7         rtbody = /<tbody/i,
8         rhtml = /<|&#?\w+;/,
9         rnocache = /<(?:script|object|embed|option|style)/i,
10         // checked="checked" or checked (html5)
11         rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
12         raction = /\=([^="'>\s]+\/)>/g,
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                 area: [ 1, "<map>", "</map>" ],
21                 _default: [ 0, "", "" ]
22         };
23
24 wrapMap.optgroup = wrapMap.option;
25 wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
26 wrapMap.th = wrapMap.td;
27
28 // IE can't serialize <link> and <script> tags normally
29 if ( !jQuery.support.htmlSerialize ) {
30         wrapMap._default = [ 1, "div<div>", "</div>" ];
31 }
32
33 jQuery.fn.extend({
34         text: function( text ) {
35                 if ( jQuery.isFunction(text) ) {
36                         return this.each(function(i) {
37                                 var self = jQuery(this);
38                                 self.text( text.call(this, i, self.text()) );
39                         });
40                 }
41
42                 if ( typeof text !== "object" && text !== undefined ) {
43                         return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
44                 }
45
46                 return jQuery.text( this );
47         },
48
49         wrapAll: function( html ) {
50                 if ( jQuery.isFunction( html ) ) {
51                         return this.each(function(i) {
52                                 jQuery(this).wrapAll( html.call(this, i) );
53                         });
54                 }
55
56                 if ( this[0] ) {
57                         // The elements to wrap the target around
58                         var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
59
60                         if ( this[0].parentNode ) {
61                                 wrap.insertBefore( this[0] );
62                         }
63
64                         wrap.map(function() {
65                                 var elem = this;
66
67                                 while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
68                                         elem = elem.firstChild;
69                                 }
70
71                                 return elem;
72                         }).append(this);
73                 }
74
75                 return this;
76         },
77
78         wrapInner: function( html ) {
79                 if ( jQuery.isFunction( html ) ) {
80                         return this.each(function(i) {
81                                 jQuery(this).wrapInner( html.call(this, i) );
82                         });
83                 }
84
85                 return this.each(function() {
86                         var self = jQuery( this ), contents = self.contents();
87
88                         if ( contents.length ) {
89                                 contents.wrapAll( html );
90
91                         } else {
92                                 self.append( html );
93                         }
94                 });
95         },
96
97         wrap: function( html ) {
98                 return this.each(function() {
99                         jQuery( this ).wrapAll( html );
100                 });
101         },
102
103         unwrap: function() {
104                 return this.parent().each(function() {
105                         if ( !jQuery.nodeName( this, "body" ) ) {
106                                 jQuery( this ).replaceWith( this.childNodes );
107                         }
108                 }).end();
109         },
110
111         append: function() {
112                 return this.domManip(arguments, true, function( elem ) {
113                         if ( this.nodeType === 1 ) {
114                                 this.appendChild( elem );
115                         }
116                 });
117         },
118
119         prepend: function() {
120                 return this.domManip(arguments, true, function( elem ) {
121                         if ( this.nodeType === 1 ) {
122                                 this.insertBefore( elem, this.firstChild );
123                         }
124                 });
125         },
126
127         before: function() {
128                 if ( this[0] && this[0].parentNode ) {
129                         return this.domManip(arguments, false, function( elem ) {
130                                 this.parentNode.insertBefore( elem, this );
131                         });
132                 } else if ( arguments.length ) {
133                         var set = jQuery(arguments[0]);
134                         set.push.apply( set, this.toArray() );
135                         return this.pushStack( set, "before", arguments );
136                 }
137         },
138
139         after: function() {
140                 if ( this[0] && this[0].parentNode ) {
141                         return this.domManip(arguments, false, function( elem ) {
142                                 this.parentNode.insertBefore( elem, this.nextSibling );
143                         });
144                 } else if ( arguments.length ) {
145                         var set = this.pushStack( this, "after", arguments );
146                         set.push.apply( set, jQuery(arguments[0]).toArray() );
147                         return set;
148                 }
149         },
150         
151         // keepData is for internal use only--do not document
152         remove: function( selector, keepData ) {
153                 for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
154                         if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
155                                 if ( !keepData && elem.nodeType === 1 ) {
156                                         jQuery.cleanData( elem.getElementsByTagName("*") );
157                                         jQuery.cleanData( [ elem ] );
158                                 }
159
160                                 if ( elem.parentNode ) {
161                                          elem.parentNode.removeChild( elem );
162                                 }
163                         }
164                 }
165                 
166                 return this;
167         },
168
169         empty: function() {
170                 for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
171                         // Remove element nodes and prevent memory leaks
172                         if ( elem.nodeType === 1 ) {
173                                 jQuery.cleanData( elem.getElementsByTagName("*") );
174                         }
175
176                         // Remove any remaining nodes
177                         while ( elem.firstChild ) {
178                                 elem.removeChild( elem.firstChild );
179                         }
180                 }
181                 
182                 return this;
183         },
184
185         clone: function( events ) {
186                 // Do the clone
187                 var ret = this.map(function() {
188                         if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
189                                 // IE copies events bound via attachEvent when
190                                 // using cloneNode. Calling detachEvent on the
191                                 // clone will also remove the events from the orignal
192                                 // In order to get around this, we use innerHTML.
193                                 // Unfortunately, this means some modifications to
194                                 // attributes in IE that are actually only stored
195                                 // as properties will not be copied (such as the
196                                 // the name attribute on an input).
197                                 var html = this.outerHTML, ownerDocument = this.ownerDocument;
198                                 if ( !html ) {
199                                         var div = ownerDocument.createElement("div");
200                                         div.appendChild( this.cloneNode(true) );
201                                         html = div.innerHTML;
202                                 }
203
204                                 return jQuery.clean([html.replace(rinlinejQuery, "")
205                                         // Handle the case in IE 8 where action=/test/> self-closes a tag
206                                         .replace(raction, '="$1">')
207                                         .replace(rleadingWhitespace, "")], ownerDocument)[0];
208                         } else {
209                                 return this.cloneNode(true);
210                         }
211                 });
212
213                 // Copy the events from the original to the clone
214                 if ( events === true ) {
215                         cloneCopyEvent( this, ret );
216                         cloneCopyEvent( this.find("*"), ret.find("*") );
217                 }
218
219                 // Return the cloned set
220                 return ret;
221         },
222
223         html: function( value ) {
224                 if ( value === undefined ) {
225                         return this[0] && this[0].nodeType === 1 ?
226                                 this[0].innerHTML.replace(rinlinejQuery, "") :
227                                 null;
228
229                 // See if we can take a shortcut and just use innerHTML
230                 } else if ( typeof value === "string" && !rnocache.test( value ) &&
231                         (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
232                         !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
233
234                         value = value.replace(rxhtmlTag, "<$1></$2>");
235
236                         try {
237                                 for ( var i = 0, l = this.length; i < l; i++ ) {
238                                         // Remove element nodes and prevent memory leaks
239                                         if ( this[i].nodeType === 1 ) {
240                                                 jQuery.cleanData( this[i].getElementsByTagName("*") );
241                                                 this[i].innerHTML = value;
242                                         }
243                                 }
244
245                         // If using innerHTML throws an exception, use the fallback method
246                         } catch(e) {
247                                 this.empty().append( value );
248                         }
249
250                 } else if ( jQuery.isFunction( value ) ) {
251                         this.each(function(i){
252                                 var self = jQuery(this);
253                                 self.html( value.call(this, i, self.html()) );
254                         });
255
256                 } else {
257                         this.empty().append( value );
258                 }
259
260                 return this;
261         },
262
263         replaceWith: function( value ) {
264                 if ( this[0] && this[0].parentNode ) {
265                         // Make sure that the elements are removed from the DOM before they are inserted
266                         // this can help fix replacing a parent with child elements
267                         if ( jQuery.isFunction( value ) ) {
268                                 return this.each(function(i) {
269                                         var self = jQuery(this), old = self.html();
270                                         self.replaceWith( value.call( this, i, old ) );
271                                 });
272                         }
273
274                         if ( typeof value !== "string" ) {
275                                 value = jQuery(value).detach();
276                         }
277
278                         return this.each(function() {
279                                 var next = this.nextSibling, parent = this.parentNode;
280
281                                 jQuery(this).remove();
282
283                                 if ( next ) {
284                                         jQuery(next).before( value );
285                                 } else {
286                                         jQuery(parent).append( value );
287                                 }
288                         });
289                 } else {
290                         return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
291                 }
292         },
293
294         detach: function( selector ) {
295                 return this.remove( selector, true );
296         },
297
298         domManip: function( args, table, callback ) {
299                 var results, first, value = args[0], scripts = [], fragment, parent;
300
301                 // We can't cloneNode fragments that contain checked, in WebKit
302                 if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
303                         return this.each(function() {
304                                 jQuery(this).domManip( args, table, callback, true );
305                         });
306                 }
307
308                 if ( jQuery.isFunction(value) ) {
309                         return this.each(function(i) {
310                                 var self = jQuery(this);
311                                 args[0] = value.call(this, i, table ? self.html() : undefined);
312                                 self.domManip( args, table, callback );
313                         });
314                 }
315
316                 if ( this[0] ) {
317                         parent = value && value.parentNode;
318
319                         // If we're in a fragment, just use that instead of building a new one
320                         if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
321                                 results = { fragment: parent };
322
323                         } else {
324                                 results = jQuery.buildFragment( args, this, scripts );
325                         }
326                         
327                         fragment = results.fragment;
328                         
329                         if ( fragment.childNodes.length === 1 ) {
330                                 first = fragment = fragment.firstChild;
331                         } else {
332                                 first = fragment.firstChild;
333                         }
334
335                         if ( first ) {
336                                 table = table && jQuery.nodeName( first, "tr" );
337
338                                 for ( var i = 0, l = this.length; i < l; i++ ) {
339                                         callback.call(
340                                                 table ?
341                                                         root(this[i], first) :
342                                                         this[i],
343                                                 i > 0 || results.cacheable || this.length > 1  ?
344                                                         fragment.cloneNode(true) :
345                                                         fragment
346                                         );
347                                 }
348                         }
349
350                         if ( scripts.length ) {
351                                 jQuery.each( scripts, evalScript );
352                         }
353                 }
354
355                 return this;
356         }
357 });
358
359 function root( elem, cur ) {
360         return jQuery.nodeName(elem, "table") ?
361                 (elem.getElementsByTagName("tbody")[0] ||
362                 elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
363                 elem;
364 }
365
366 function cloneCopyEvent(orig, ret) {
367         var i = 0;
368
369         ret.each(function() {
370                 if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) {
371                         return;
372                 }
373
374                 var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events;
375
376                 if ( events ) {
377                         delete curData.handle;
378                         curData.events = {};
379
380                         for ( var type in events ) {
381                                 for ( var handler in events[ type ] ) {
382                                         jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
383                                 }
384                         }
385                 }
386         });
387 }
388
389 jQuery.buildFragment = function( args, nodes, scripts ) {
390         var fragment, cacheable, cacheresults,
391                 doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
392
393         // Only cache "small" (1/2 KB) strings that are associated with the main document
394         // Cloning options loses the selected state, so don't cache them
395         // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
396         // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
397         if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
398                 !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
399
400                 cacheable = true;
401                 cacheresults = jQuery.fragments[ args[0] ];
402                 if ( cacheresults ) {
403                         if ( cacheresults !== 1 ) {
404                                 fragment = cacheresults;
405                         }
406                 }
407         }
408
409         if ( !fragment ) {
410                 fragment = doc.createDocumentFragment();
411                 jQuery.clean( args, doc, fragment, scripts );
412         }
413
414         if ( cacheable ) {
415                 jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
416         }
417
418         return { fragment: fragment, cacheable: cacheable };
419 };
420
421 jQuery.fragments = {};
422
423 jQuery.each({
424         appendTo: "append",
425         prependTo: "prepend",
426         insertBefore: "before",
427         insertAfter: "after",
428         replaceAll: "replaceWith"
429 }, function( name, original ) {
430         jQuery.fn[ name ] = function( selector ) {
431                 var ret = [], insert = jQuery( selector ),
432                         parent = this.length === 1 && this[0].parentNode;
433                 
434                 if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
435                         insert[ original ]( this[0] );
436                         return this;
437                         
438                 } else {
439                         for ( var i = 0, l = insert.length; i < l; i++ ) {
440                                 var elems = (i > 0 ? this.clone(true) : this).get();
441                                 jQuery( insert[i] )[ original ]( elems );
442                                 ret = ret.concat( elems );
443                         }
444                 
445                         return this.pushStack( ret, name, insert.selector );
446                 }
447         };
448 });
449
450 jQuery.extend({
451         clean: function( elems, context, fragment, scripts ) {
452                 context = context || document;
453
454                 // !context.createElement fails in IE with an error but returns typeof 'object'
455                 if ( typeof context.createElement === "undefined" ) {
456                         context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
457                 }
458
459                 var ret = [];
460
461                 for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
462                         if ( typeof elem === "number" ) {
463                                 elem += "";
464                         }
465
466                         if ( !elem ) {
467                                 continue;
468                         }
469
470                         // Convert html string into DOM nodes
471                         if ( typeof elem === "string" && !rhtml.test( elem ) ) {
472                                 elem = context.createTextNode( elem );
473
474                         } else if ( typeof elem === "string" ) {
475                                 // Fix "XHTML"-style tags in all browsers
476                                 elem = elem.replace(rxhtmlTag, "<$1></$2>");
477
478                                 // Trim whitespace, otherwise indexOf won't work as expected
479                                 var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
480                                         wrap = wrapMap[ tag ] || wrapMap._default,
481                                         depth = wrap[0],
482                                         div = context.createElement("div");
483
484                                 // Go to html and back, then peel off extra wrappers
485                                 div.innerHTML = wrap[1] + elem + wrap[2];
486
487                                 // Move to the right depth
488                                 while ( depth-- ) {
489                                         div = div.lastChild;
490                                 }
491
492                                 // Remove IE's autoinserted <tbody> from table fragments
493                                 if ( !jQuery.support.tbody ) {
494
495                                         // String was a <table>, *may* have spurious <tbody>
496                                         var hasBody = rtbody.test(elem),
497                                                 tbody = tag === "table" && !hasBody ?
498                                                         div.firstChild && div.firstChild.childNodes :
499
500                                                         // String was a bare <thead> or <tfoot>
501                                                         wrap[1] === "<table>" && !hasBody ?
502                                                                 div.childNodes :
503                                                                 [];
504
505                                         for ( var j = tbody.length - 1; j >= 0 ; --j ) {
506                                                 if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
507                                                         tbody[ j ].parentNode.removeChild( tbody[ j ] );
508                                                 }
509                                         }
510
511                                 }
512
513                                 // IE completely kills leading whitespace when innerHTML is used
514                                 if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
515                                         div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
516                                 }
517
518                                 elem = div.childNodes;
519                         }
520
521                         if ( elem.nodeType ) {
522                                 ret.push( elem );
523                         } else {
524                                 ret = jQuery.merge( ret, elem );
525                         }
526                 }
527
528                 if ( fragment ) {
529                         for ( i = 0; ret[i]; i++ ) {
530                                 if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
531                                         scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
532                                 
533                                 } else {
534                                         if ( ret[i].nodeType === 1 ) {
535                                                 ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
536                                         }
537                                         fragment.appendChild( ret[i] );
538                                 }
539                         }
540                 }
541
542                 return ret;
543         },
544         
545         cleanData: function( elems ) {
546                 var data, id, cache = jQuery.cache,
547                         special = jQuery.event.special,
548                         deleteExpando = jQuery.support.deleteExpando;
549                 
550                 for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
551                         if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
552                                 continue;
553                         }
554
555                         id = elem[ jQuery.expando ];
556                         
557                         if ( id ) {
558                                 data = cache[ id ];
559                                 
560                                 if ( data && data.events ) {
561                                         for ( var type in data.events ) {
562                                                 if ( special[ type ] ) {
563                                                         jQuery.event.remove( elem, type );
564
565                                                 } else {
566                                                         jQuery.removeEvent( elem, type, data.handle );
567                                                 }
568                                         }
569                                 }
570                                 
571                                 if ( deleteExpando ) {
572                                         delete elem[ jQuery.expando ];
573
574                                 } else if ( elem.removeAttribute ) {
575                                         elem.removeAttribute( jQuery.expando );
576                                 }
577                                 
578                                 delete cache[ id ];
579                         }
580                 }
581         }
582 });
583
584 function evalScript( i, elem ) {
585         if ( elem.src ) {
586                 jQuery.ajax({
587                         url: elem.src,
588                         async: false,
589                         dataType: "script"
590                 });
591         } else {
592                 jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
593         }
594
595         if ( elem.parentNode ) {
596                 elem.parentNode.removeChild( elem );
597         }
598 }
599
600 })( jQuery );