24409d2c5c048ce7f4f7c9c9ad770a0a51cce7d4
[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         wrapMap = {
13                 option: [ 1, "<select multiple='multiple'>", "</select>" ],
14                 legend: [ 1, "<fieldset>", "</fieldset>" ],
15                 thead: [ 1, "<table>", "</table>" ],
16                 tr: [ 2, "<table><tbody>", "</tbody></table>" ],
17                 td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
18                 col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
19                 area: [ 1, "<map>", "</map>" ],
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 ( jQuery.isFunction(text) ) {
35                         return this.each(function(i) {
36                                 var self = jQuery( this );
37
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 ),
87                                 contents = self.contents();
88
89                         if ( contents.length ) {
90                                 contents.wrapAll( html );
91
92                         } else {
93                                 self.append( html );
94                         }
95                 });
96         },
97
98         wrap: function( html ) {
99                 return this.each(function() {
100                         jQuery( this ).wrapAll( html );
101                 });
102         },
103
104         unwrap: function() {
105                 return this.parent().each(function() {
106                         if ( !jQuery.nodeName( this, "body" ) ) {
107                                 jQuery( this ).replaceWith( this.childNodes );
108                         }
109                 }).end();
110         },
111
112         append: function() {
113                 return this.domManip(arguments, true, function( elem ) {
114                         if ( this.nodeType === 1 ) {
115                                 this.appendChild( elem );
116                         }
117                 });
118         },
119
120         prepend: function() {
121                 return this.domManip(arguments, true, function( elem ) {
122                         if ( this.nodeType === 1 ) {
123                                 this.insertBefore( elem, this.firstChild );
124                         }
125                 });
126         },
127
128         before: function() {
129                 if ( this[0] && this[0].parentNode ) {
130                         return this.domManip(arguments, false, function( elem ) {
131                                 this.parentNode.insertBefore( elem, this );
132                         });
133                 } else if ( arguments.length ) {
134                         var set = jQuery(arguments[0]);
135                         set.push.apply( set, this.toArray() );
136                         return this.pushStack( set, "before", arguments );
137                 }
138         },
139
140         after: function() {
141                 if ( this[0] && this[0].parentNode ) {
142                         return this.domManip(arguments, false, function( elem ) {
143                                 this.parentNode.insertBefore( elem, this.nextSibling );
144                         });
145                 } else if ( arguments.length ) {
146                         var set = this.pushStack( this, "after", arguments );
147                         set.push.apply( set, jQuery(arguments[0]).toArray() );
148                         return set;
149                 }
150         },
151
152         // keepData is for internal use only--do not document
153         remove: function( selector, keepData ) {
154                 for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
155                         if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
156                                 if ( !keepData && elem.nodeType === 1 ) {
157                                         jQuery.cleanData( elem.getElementsByTagName("*") );
158                                         jQuery.cleanData( [ elem ] );
159                                 }
160
161                                 if ( elem.parentNode ) {
162                                          elem.parentNode.removeChild( elem );
163                                 }
164                         }
165                 }
166
167                 return this;
168         },
169
170         empty: function() {
171                 for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
172                         // Remove element nodes and prevent memory leaks
173                         if ( elem.nodeType === 1 ) {
174                                 jQuery.cleanData( elem.getElementsByTagName("*") );
175                         }
176
177                         // Remove any remaining nodes
178                         while ( elem.firstChild ) {
179                                 elem.removeChild( elem.firstChild );
180                         }
181                 }
182
183                 return this;
184         },
185
186         clone: function( events ) {
187                 // Do the clone
188                 var ret = this.map(function() {
189                         var clone = this.cloneNode(true);
190                         if ( !jQuery.support.noCloneEvent && (this.nodeType === 1 || this.nodeType === 11) && !jQuery.isXMLDoc(this) ) {
191                                 // IE copies events bound via attachEvent when using cloneNode.
192                                 // Calling detachEvent on the clone will also remove the events
193                                 // from the original. In order to get around this, we use some
194                                 // proprietary methods to clear the events. Thanks to MooTools
195                                 // guys for this hotness.
196
197                                 // Using Sizzle here is crazy slow, so we use getElementsByTagName
198                                 // instead
199                                 var srcElements = this.getElementsByTagName("*"),
200                                         destElements = clone.getElementsByTagName("*");
201
202                                 // Weird iteration because IE will replace the length property
203                                 // with an element if you are cloning the body and one of the
204                                 // elements on the page has a name or id of "length"
205                                 for ( var i = 0; srcElements[i]; ++i ) {
206                                         cloneFixAttributes( srcElements[i], destElements[i] );
207                                 }
208
209                                 cloneFixAttributes( this, clone );
210                         }
211
212                         return clone;
213                 });
214
215                 // Copy the events from the original to the clone
216                 if ( events === true ) {
217                         cloneCopyEvent( this, ret );
218                         cloneCopyEvent( this.find("*"), ret.find("*") );
219                 }
220
221                 // Return the cloned set
222                 return ret;
223         },
224
225         html: function( value ) {
226                 if ( value === undefined ) {
227                         return this[0] && this[0].nodeType === 1 ?
228                                 this[0].innerHTML.replace(rinlinejQuery, "") :
229                                 null;
230
231                 // See if we can take a shortcut and just use innerHTML
232                 } else if ( typeof value === "string" && !rnocache.test( value ) &&
233                         (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
234                         !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
235
236                         value = value.replace(rxhtmlTag, "<$1></$2>");
237
238                         try {
239                                 for ( var i = 0, l = this.length; i < l; i++ ) {
240                                         // Remove element nodes and prevent memory leaks
241                                         if ( this[i].nodeType === 1 ) {
242                                                 jQuery.cleanData( this[i].getElementsByTagName("*") );
243                                                 this[i].innerHTML = value;
244                                         }
245                                 }
246
247                         // If using innerHTML throws an exception, use the fallback method
248                         } catch(e) {
249                                 this.empty().append( value );
250                         }
251
252                 } else if ( jQuery.isFunction( value ) ) {
253                         this.each(function(i){
254                                 var self = jQuery( this );
255
256                                 self.html( value.call(this, i, self.html()) );
257                         });
258
259                 } else {
260                         this.empty().append( value );
261                 }
262
263                 return this;
264         },
265
266         replaceWith: function( value ) {
267                 if ( this[0] && this[0].parentNode ) {
268                         // Make sure that the elements are removed from the DOM before they are inserted
269                         // this can help fix replacing a parent with child elements
270                         if ( jQuery.isFunction( value ) ) {
271                                 return this.each(function(i) {
272                                         var self = jQuery(this), old = self.html();
273                                         self.replaceWith( value.call( this, i, old ) );
274                                 });
275                         }
276
277                         if ( typeof value !== "string" ) {
278                                 value = jQuery( value ).detach();
279                         }
280
281                         return this.each(function() {
282                                 var next = this.nextSibling,
283                                         parent = this.parentNode;
284
285                                 jQuery( this ).remove();
286
287                                 if ( next ) {
288                                         jQuery(next).before( value );
289                                 } else {
290                                         jQuery(parent).append( value );
291                                 }
292                         });
293                 } else {
294                         return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
295                 }
296         },
297
298         detach: function( selector ) {
299                 return this.remove( selector, true );
300         },
301
302         domManip: function( args, table, callback ) {
303                 var results, first, fragment, parent,
304                         value = args[0],
305                         scripts = [];
306
307                 // We can't cloneNode fragments that contain checked, in WebKit
308                 if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
309                         return this.each(function() {
310                                 jQuery(this).domManip( args, table, callback, true );
311                         });
312                 }
313
314                 if ( jQuery.isFunction(value) ) {
315                         return this.each(function(i) {
316                                 var self = jQuery(this);
317                                 args[0] = value.call(this, i, table ? self.html() : undefined);
318                                 self.domManip( args, table, callback );
319                         });
320                 }
321
322                 if ( this[0] ) {
323                         parent = value && value.parentNode;
324
325                         // If we're in a fragment, just use that instead of building a new one
326                         if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
327                                 results = { fragment: parent };
328
329                         } else {
330                                 results = jQuery.buildFragment( args, this, scripts );
331                         }
332
333                         fragment = results.fragment;
334
335                         if ( fragment.childNodes.length === 1 ) {
336                                 first = fragment = fragment.firstChild;
337                         } else {
338                                 first = fragment.firstChild;
339                         }
340
341                         if ( first ) {
342                                 table = table && jQuery.nodeName( first, "tr" );
343
344                                 for ( var i = 0, l = this.length; i < l; i++ ) {
345                                         callback.call(
346                                                 table ?
347                                                         root(this[i], first) :
348                                                         this[i],
349                                                 i > 0 || results.cacheable || this.length > 1  ?
350                                                         jQuery(fragment).clone(true)[0] :
351                                                         fragment
352                                         );
353                                 }
354                         }
355
356                         if ( scripts.length ) {
357                                 jQuery.each( scripts, evalScript );
358                         }
359                 }
360
361                 return this;
362         }
363 });
364
365 function root( elem, cur ) {
366         return jQuery.nodeName(elem, "table") ?
367                 (elem.getElementsByTagName("tbody")[0] ||
368                 elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
369                 elem;
370 }
371
372 function cloneCopyEvent(orig, ret) {
373         var i = 0;
374
375         ret.each(function() {
376                 if ( this.nodeType !== 1 || this.nodeName !== (orig[i] && orig[i].nodeName) ) {
377                         return;
378                 }
379
380                 var oldData = jQuery.data( orig[i++] ),
381                         curData = jQuery.data( this, oldData ),
382                         events = oldData && oldData.events;
383
384                 if ( events ) {
385                         delete curData.handle;
386                         curData.events = {};
387
388                         for ( var type in events ) {
389                                 for ( var handler in events[ type ] ) {
390                                         jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
391                                 }
392                         }
393                 }
394         });
395 }
396
397 function cloneFixAttributes(src, dest) {
398         // We do not need to do anything for non-Elements
399         if ( dest.nodeType !== 1 ) {
400                 return;
401         }
402
403         var nodeName = dest.nodeName.toLowerCase();
404
405         // clearAttributes removes the attributes, which we don't want,
406         // but also removes the attachEvent events, which we *do* want
407         dest.clearAttributes();
408
409         // mergeAttributes, in contrast, only merges back on the
410         // original attributes, not the events
411         dest.mergeAttributes(src);
412
413         // IE6-8 fail to clone children inside object elements that use
414         // the proprietary classid attribute value (rather than the type
415         // attribute) to identify the type of content to display
416         if ( nodeName === "object" ) {
417                 dest.outerHTML = src.outerHTML;
418         }
419
420         // IE6-? fails to persist the checked state of a cloned checkbox
421         // or radio button
422         else if ( nodeName === "input" && src.checked ) {
423                 dest.defaultChecked = dest.checked = src.checked;
424         }
425
426         // IE6-? fails to return the selected option to the default selected
427         // state when cloning options
428         else if ( nodeName === "option" ) {
429                 dest.selected = src.defaultSelected;
430         }
431
432         // Event data gets referenced instead of copied if the expando
433         // gets copied too
434         dest.removeAttribute( jQuery.expando );
435 }
436
437 jQuery.buildFragment = function( args, nodes, scripts ) {
438         var fragment, cacheable, cacheresults,
439                 doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
440
441         // Only cache "small" (1/2 KB) strings that are associated with the main document
442         // Cloning options loses the selected state, so don't cache them
443         // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
444         // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
445         if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
446                 !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
447
448                 cacheable = true;
449                 cacheresults = jQuery.fragments[ args[0] ];
450                 if ( cacheresults ) {
451                         if ( cacheresults !== 1 ) {
452                                 fragment = cacheresults;
453                         }
454                 }
455         }
456
457         if ( !fragment ) {
458                 fragment = doc.createDocumentFragment();
459                 jQuery.clean( args, doc, fragment, scripts );
460         }
461
462         if ( cacheable ) {
463                 jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
464         }
465
466         return { fragment: fragment, cacheable: cacheable };
467 };
468
469 jQuery.fragments = {};
470
471 jQuery.each({
472         appendTo: "append",
473         prependTo: "prepend",
474         insertBefore: "before",
475         insertAfter: "after",
476         replaceAll: "replaceWith"
477 }, function( name, original ) {
478         jQuery.fn[ name ] = function( selector ) {
479                 var ret = [],
480                         insert = jQuery( selector ),
481                         parent = this.length === 1 && this[0].parentNode;
482
483                 if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
484                         insert[ original ]( this[0] );
485                         return this;
486
487                 } else {
488                         for ( var i = 0, l = insert.length; i < l; i++ ) {
489                                 var elems = (i > 0 ? this.clone(true) : this).get();
490                                 jQuery( insert[i] )[ original ]( elems );
491                                 ret = ret.concat( elems );
492                         }
493
494                         return this.pushStack( ret, name, insert.selector );
495                 }
496         };
497 });
498
499 jQuery.extend({
500         clean: function( elems, context, fragment, scripts ) {
501                 context = context || document;
502
503                 // !context.createElement fails in IE with an error but returns typeof 'object'
504                 if ( typeof context.createElement === "undefined" ) {
505                         context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
506                 }
507
508                 var ret = [];
509
510                 for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
511                         if ( typeof elem === "number" ) {
512                                 elem += "";
513                         }
514
515                         if ( !elem ) {
516                                 continue;
517                         }
518
519                         // Convert html string into DOM nodes
520                         if ( typeof elem === "string" && !rhtml.test( elem ) ) {
521                                 elem = context.createTextNode( elem );
522
523                         } else if ( typeof elem === "string" ) {
524                                 // Fix "XHTML"-style tags in all browsers
525                                 elem = elem.replace(rxhtmlTag, "<$1></$2>");
526
527                                 // Trim whitespace, otherwise indexOf won't work as expected
528                                 var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
529                                         wrap = wrapMap[ tag ] || wrapMap._default,
530                                         depth = wrap[0],
531                                         div = context.createElement("div");
532
533                                 // Go to html and back, then peel off extra wrappers
534                                 div.innerHTML = wrap[1] + elem + wrap[2];
535
536                                 // Move to the right depth
537                                 while ( depth-- ) {
538                                         div = div.lastChild;
539                                 }
540
541                                 // Remove IE's autoinserted <tbody> from table fragments
542                                 if ( !jQuery.support.tbody ) {
543
544                                         // String was a <table>, *may* have spurious <tbody>
545                                         var hasBody = rtbody.test(elem),
546                                                 tbody = tag === "table" && !hasBody ?
547                                                         div.firstChild && div.firstChild.childNodes :
548
549                                                         // String was a bare <thead> or <tfoot>
550                                                         wrap[1] === "<table>" && !hasBody ?
551                                                                 div.childNodes :
552                                                                 [];
553
554                                         for ( var j = tbody.length - 1; j >= 0 ; --j ) {
555                                                 if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
556                                                         tbody[ j ].parentNode.removeChild( tbody[ j ] );
557                                                 }
558                                         }
559
560                                 }
561
562                                 // IE completely kills leading whitespace when innerHTML is used
563                                 if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
564                                         div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
565                                 }
566
567                                 elem = div.childNodes;
568                         }
569
570                         if ( elem.nodeType ) {
571                                 ret.push( elem );
572                         } else {
573                                 ret = jQuery.merge( ret, elem );
574                         }
575                 }
576
577                 if ( fragment ) {
578                         for ( i = 0; ret[i]; i++ ) {
579                                 if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
580                                         scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
581
582                                 } else {
583                                         if ( ret[i].nodeType === 1 ) {
584                                                 ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
585                                         }
586                                         fragment.appendChild( ret[i] );
587                                 }
588                         }
589                 }
590
591                 return ret;
592         },
593
594         cleanData: function( elems ) {
595                 var data, id, cache = jQuery.cache,
596                         special = jQuery.event.special,
597                         deleteExpando = jQuery.support.deleteExpando;
598
599                 for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
600                         if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
601                                 continue;
602                         }
603
604                         id = elem[ jQuery.expando ];
605
606                         if ( id ) {
607                                 data = cache[ id ];
608
609                                 if ( data && data.events ) {
610                                         for ( var type in data.events ) {
611                                                 if ( special[ type ] ) {
612                                                         jQuery.event.remove( elem, type );
613
614                                                 } else {
615                                                         jQuery.removeEvent( elem, type, data.handle );
616                                                 }
617                                         }
618                                 }
619
620                                 if ( deleteExpando ) {
621                                         delete elem[ jQuery.expando ];
622
623                                 } else if ( elem.removeAttribute ) {
624                                         elem.removeAttribute( jQuery.expando );
625                                 }
626
627                                 delete cache[ id ];
628                         }
629                 }
630         }
631 });
632
633 function evalScript( i, elem ) {
634         if ( elem.src ) {
635                 jQuery.ajax({
636                         url: elem.src,
637                         async: false,
638                         dataType: "script"
639                 });
640         } else {
641                 jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
642         }
643
644         if ( elem.parentNode ) {
645                 elem.parentNode.removeChild( elem );
646         }
647 }
648
649 })( jQuery );