Release: push dist to same remote as project
[jquery.git] / src / manipulation.js
blob2e309f5e7cda74277f89e65c21fcd71a56e56d32
1 define([
2         "./core",
3         "./var/concat",
4         "./var/push",
5         "./core/access",
6         "./manipulation/var/rcheckableType",
7         "./manipulation/support",
8         "./data/var/dataPriv",
9         "./data/var/dataUser",
11         "./core/init",
12         "./data/accepts",
13         "./traversing",
14         "./selector",
15         "./event"
16 ], function( jQuery, concat, push, access, rcheckableType, support, dataPriv, dataUser ) {
18 var
19         rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,
20         rtagName = /<([\w:-]+)/,
21         rhtml = /<|&#?\w+;/,
22         rnoInnerhtml = /<(?:script|style|link)/i,
23         // checked="checked" or checked
24         rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
25         rscriptType = /^$|\/(?:java|ecma)script/i,
26         rscriptTypeMasked = /^true\/(.*)/,
27         rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
29         // We have to close these tags to support XHTML (#13200)
30         wrapMap = {
32                 // Support: IE9
33                 option: [ 1, "<select multiple='multiple'>", "</select>" ],
35                 thead: [ 1, "<table>", "</table>" ],
36                 col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
37                 tr: [ 2, "<table><tbody>", "</tbody></table>" ],
38                 td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
40                 _default: [ 0, "", "" ]
41         };
43 // Support: IE9
44 wrapMap.optgroup = wrapMap.option;
46 wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
47 wrapMap.th = wrapMap.td;
49 // Manipulating tables requires a tbody
50 function manipulationTarget( elem, content ) {
51         return jQuery.nodeName( elem, "table" ) &&
52                 jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
54                 elem.getElementsByTagName("tbody")[0] ||
55                         elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
56                 elem;
59 // Replace/restore the type attribute of script elements for safe DOM manipulation
60 function disableScript( elem ) {
61         elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
62         return elem;
64 function restoreScript( elem ) {
65         var match = rscriptTypeMasked.exec( elem.type );
67         if ( match ) {
68                 elem.type = match[ 1 ];
69         } else {
70                 elem.removeAttribute("type");
71         }
73         return elem;
76 // Mark scripts as having already been evaluated
77 function setGlobalEval( elems, refElements ) {
78         var i = 0,
79                 l = elems.length;
81         for ( ; i < l; i++ ) {
82                 dataPriv.set(
83                         elems[ i ], "globalEval", !refElements || dataPriv.get( refElements[ i ], "globalEval" )
84                 );
85         }
88 function cloneCopyEvent( src, dest ) {
89         var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
91         if ( dest.nodeType !== 1 ) {
92                 return;
93         }
95         // 1. Copy private data: events, handlers, etc.
96         if ( dataPriv.hasData( src ) ) {
97                 pdataOld = dataPriv.access( src );
98                 pdataCur = dataPriv.set( dest, pdataOld );
99                 events = pdataOld.events;
101                 if ( events ) {
102                         delete pdataCur.handle;
103                         pdataCur.events = {};
105                         for ( type in events ) {
106                                 for ( i = 0, l = events[ type ].length; i < l; i++ ) {
107                                         jQuery.event.add( dest, type, events[ type ][ i ] );
108                                 }
109                         }
110                 }
111         }
113         // 2. Copy user data
114         if ( dataUser.hasData( src ) ) {
115                 udataOld = dataUser.access( src );
116                 udataCur = jQuery.extend( {}, udataOld );
118                 dataUser.set( dest, udataCur );
119         }
122 function getAll( context, tag ) {
123         // Support: IE9-11+
124         // Use typeof to avoid zero-argument method invocation on host objects (#15151)
125         var ret = typeof context.getElementsByTagName !== "undefined" ?
126                         context.getElementsByTagName( tag || "*" ) :
127                         typeof context.querySelectorAll !== "undefined" ?
128                                 context.querySelectorAll( tag || "*" ) :
129                         [];
131         return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
132                 jQuery.merge( [ context ], ret ) :
133                 ret;
136 // Fix IE bugs, see support tests
137 function fixInput( src, dest ) {
138         var nodeName = dest.nodeName.toLowerCase();
140         // Fails to persist the checked state of a cloned checkbox or radio button.
141         if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
142                 dest.checked = src.checked;
144         // Fails to return the selected option to the default selected state when cloning options
145         } else if ( nodeName === "input" || nodeName === "textarea" ) {
146                 dest.defaultValue = src.defaultValue;
147         }
150 jQuery.extend({
151         clone: function( elem, dataAndEvents, deepDataAndEvents ) {
152                 var i, l, srcElements, destElements,
153                         clone = elem.cloneNode( true ),
154                         inPage = jQuery.contains( elem.ownerDocument, elem );
156                 // Fix IE cloning issues
157                 if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
158                                 !jQuery.isXMLDoc( elem ) ) {
160                         // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
161                         destElements = getAll( clone );
162                         srcElements = getAll( elem );
164                         for ( i = 0, l = srcElements.length; i < l; i++ ) {
165                                 fixInput( srcElements[ i ], destElements[ i ] );
166                         }
167                 }
169                 // Copy the events from the original to the clone
170                 if ( dataAndEvents ) {
171                         if ( deepDataAndEvents ) {
172                                 srcElements = srcElements || getAll( elem );
173                                 destElements = destElements || getAll( clone );
175                                 for ( i = 0, l = srcElements.length; i < l; i++ ) {
176                                         cloneCopyEvent( srcElements[ i ], destElements[ i ] );
177                                 }
178                         } else {
179                                 cloneCopyEvent( elem, clone );
180                         }
181                 }
183                 // Preserve script evaluation history
184                 destElements = getAll( clone, "script" );
185                 if ( destElements.length > 0 ) {
186                         setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
187                 }
189                 // Return the cloned set
190                 return clone;
191         },
193         buildFragment: function( elems, context, scripts, selection ) {
194                 var elem, tmp, tag, wrap, contains, j,
195                         fragment = context.createDocumentFragment(),
196                         nodes = [],
197                         i = 0,
198                         l = elems.length;
200                 for ( ; i < l; i++ ) {
201                         elem = elems[ i ];
203                         if ( elem || elem === 0 ) {
205                                 // Add nodes directly
206                                 if ( jQuery.type( elem ) === "object" ) {
207                                         // Support: Android<4.1, PhantomJS<2
208                                         // push.apply(_, arraylike) throws on ancient WebKit
209                                         jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
211                                 // Convert non-html into a text node
212                                 } else if ( !rhtml.test( elem ) ) {
213                                         nodes.push( context.createTextNode( elem ) );
215                                 // Convert html into DOM nodes
216                                 } else {
217                                         tmp = tmp || fragment.appendChild( context.createElement("div") );
219                                         // Deserialize a standard representation
220                                         tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
221                                         wrap = wrapMap[ tag ] || wrapMap._default;
222                                         tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
224                                         // Descend through wrappers to the right content
225                                         j = wrap[ 0 ];
226                                         while ( j-- ) {
227                                                 tmp = tmp.lastChild;
228                                         }
230                                         // Support: Android<4.1, PhantomJS<2
231                                         // push.apply(_, arraylike) throws on ancient WebKit
232                                         jQuery.merge( nodes, tmp.childNodes );
234                                         // Remember the top-level container
235                                         tmp = fragment.firstChild;
237                                         // Ensure the created nodes are orphaned (#12392)
238                                         tmp.textContent = "";
239                                 }
240                         }
241                 }
243                 // Remove wrapper from fragment
244                 fragment.textContent = "";
246                 i = 0;
247                 while ( (elem = nodes[ i++ ]) ) {
249                         // #4087 - If origin and destination elements are the same, and this is
250                         // that element, do not do anything
251                         if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
252                                 continue;
253                         }
255                         contains = jQuery.contains( elem.ownerDocument, elem );
257                         // Append to fragment
258                         tmp = getAll( fragment.appendChild( elem ), "script" );
260                         // Preserve script evaluation history
261                         if ( contains ) {
262                                 setGlobalEval( tmp );
263                         }
265                         // Capture executables
266                         if ( scripts ) {
267                                 j = 0;
268                                 while ( (elem = tmp[ j++ ]) ) {
269                                         if ( rscriptType.test( elem.type || "" ) ) {
270                                                 scripts.push( elem );
271                                         }
272                                 }
273                         }
274                 }
276                 return fragment;
277         },
279         cleanData: function( elems ) {
280                 var data, elem, type, key,
281                         special = jQuery.event.special,
282                         i = 0;
284                 for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
285                         if ( jQuery.acceptData( elem ) ) {
286                                 key = elem[ dataPriv.expando ];
288                                 if ( key && (data = dataPriv.cache[ key ]) ) {
289                                         if ( data.events ) {
290                                                 for ( type in data.events ) {
291                                                         if ( special[ type ] ) {
292                                                                 jQuery.event.remove( elem, type );
294                                                         // This is a shortcut to avoid jQuery.event.remove's overhead
295                                                         } else {
296                                                                 jQuery.removeEvent( elem, type, data.handle );
297                                                         }
298                                                 }
299                                         }
300                                         if ( dataPriv.cache[ key ] ) {
301                                                 // Discard any remaining `private` data
302                                                 delete dataPriv.cache[ key ];
303                                         }
304                                 }
305                         }
306                         // Discard any remaining `user` data
307                         delete dataUser.cache[ elem[ dataUser.expando ] ];
308                 }
309         }
312 jQuery.fn.extend({
313         text: function( value ) {
314                 return access( this, function( value ) {
315                         return value === undefined ?
316                                 jQuery.text( this ) :
317                                 this.empty().each(function() {
318                                         if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
319                                                 this.textContent = value;
320                                         }
321                                 });
322                 }, null, value, arguments.length );
323         },
325         append: function() {
326                 return this.domManip( arguments, function( elem ) {
327                         if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
328                                 var target = manipulationTarget( this, elem );
329                                 target.appendChild( elem );
330                         }
331                 });
332         },
334         prepend: function() {
335                 return this.domManip( arguments, function( elem ) {
336                         if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
337                                 var target = manipulationTarget( this, elem );
338                                 target.insertBefore( elem, target.firstChild );
339                         }
340                 });
341         },
343         before: function() {
344                 return this.domManip( arguments, function( elem ) {
345                         if ( this.parentNode ) {
346                                 this.parentNode.insertBefore( elem, this );
347                         }
348                 });
349         },
351         after: function() {
352                 return this.domManip( arguments, function( elem ) {
353                         if ( this.parentNode ) {
354                                 this.parentNode.insertBefore( elem, this.nextSibling );
355                         }
356                 });
357         },
359         remove: function( selector, keepData /* Internal Use Only */ ) {
360                 var elem,
361                         elems = selector ? jQuery.filter( selector, this ) : this,
362                         i = 0;
364                 for ( ; (elem = elems[i]) != null; i++ ) {
365                         if ( !keepData && elem.nodeType === 1 ) {
366                                 jQuery.cleanData( getAll( elem ) );
367                         }
369                         if ( elem.parentNode ) {
370                                 if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
371                                         setGlobalEval( getAll( elem, "script" ) );
372                                 }
373                                 elem.parentNode.removeChild( elem );
374                         }
375                 }
377                 return this;
378         },
380         empty: function() {
381                 var elem,
382                         i = 0;
384                 for ( ; (elem = this[i]) != null; i++ ) {
385                         if ( elem.nodeType === 1 ) {
387                                 // Prevent memory leaks
388                                 jQuery.cleanData( getAll( elem, false ) );
390                                 // Remove any remaining nodes
391                                 elem.textContent = "";
392                         }
393                 }
395                 return this;
396         },
398         clone: function( dataAndEvents, deepDataAndEvents ) {
399                 dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
400                 deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
402                 return this.map(function() {
403                         return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
404                 });
405         },
407         html: function( value ) {
408                 return access( this, function( value ) {
409                         var elem = this[ 0 ] || {},
410                                 i = 0,
411                                 l = this.length;
413                         if ( value === undefined && elem.nodeType === 1 ) {
414                                 return elem.innerHTML;
415                         }
417                         // See if we can take a shortcut and just use innerHTML
418                         if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
419                                 !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
421                                 value = value.replace( rxhtmlTag, "<$1></$2>" );
423                                 try {
424                                         for ( ; i < l; i++ ) {
425                                                 elem = this[ i ] || {};
427                                                 // Remove element nodes and prevent memory leaks
428                                                 if ( elem.nodeType === 1 ) {
429                                                         jQuery.cleanData( getAll( elem, false ) );
430                                                         elem.innerHTML = value;
431                                                 }
432                                         }
434                                         elem = 0;
436                                 // If using innerHTML throws an exception, use the fallback method
437                                 } catch ( e ) {}
438                         }
440                         if ( elem ) {
441                                 this.empty().append( value );
442                         }
443                 }, null, value, arguments.length );
444         },
446         replaceWith: function() {
447                 var arg = arguments[ 0 ];
449                 // Make the changes, replacing each context element with the new content
450                 this.domManip( arguments, function( elem ) {
451                         arg = this.parentNode;
453                         jQuery.cleanData( getAll( this ) );
455                         if ( arg ) {
456                                 arg.replaceChild( elem, this );
457                         }
458                 });
460                 // Force removal if there was no new content (e.g., from empty arguments)
461                 return arg && (arg.length || arg.nodeType) ? this : this.remove();
462         },
464         detach: function( selector ) {
465                 return this.remove( selector, true );
466         },
468         domManip: function( args, callback ) {
470                 // Flatten any nested arrays
471                 args = concat.apply( [], args );
473                 var fragment, first, scripts, hasScripts, node, doc,
474                         i = 0,
475                         l = this.length,
476                         set = this,
477                         iNoClone = l - 1,
478                         value = args[ 0 ],
479                         isFunction = jQuery.isFunction( value );
481                 // We can't cloneNode fragments that contain checked, in WebKit
482                 if ( isFunction ||
483                                 ( l > 1 && typeof value === "string" &&
484                                         !support.checkClone && rchecked.test( value ) ) ) {
485                         return this.each(function( index ) {
486                                 var self = set.eq( index );
487                                 if ( isFunction ) {
488                                         args[ 0 ] = value.call( this, index, self.html() );
489                                 }
490                                 self.domManip( args, callback );
491                         });
492                 }
494                 if ( l ) {
495                         fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
496                         first = fragment.firstChild;
498                         if ( fragment.childNodes.length === 1 ) {
499                                 fragment = first;
500                         }
502                         if ( first ) {
503                                 scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
504                                 hasScripts = scripts.length;
506                                 // Use the original fragment for the last item
507                                 // instead of the first because it can end up
508                                 // being emptied incorrectly in certain situations (#8070).
509                                 for ( ; i < l; i++ ) {
510                                         node = fragment;
512                                         if ( i !== iNoClone ) {
513                                                 node = jQuery.clone( node, true, true );
515                                                 // Keep references to cloned scripts for later restoration
516                                                 if ( hasScripts ) {
517                                                         // Support: Android<4.1, PhantomJS<2
518                                                         // push.apply(_, arraylike) throws on ancient WebKit
519                                                         jQuery.merge( scripts, getAll( node, "script" ) );
520                                                 }
521                                         }
523                                         callback.call( this[ i ], node, i );
524                                 }
526                                 if ( hasScripts ) {
527                                         doc = scripts[ scripts.length - 1 ].ownerDocument;
529                                         // Reenable scripts
530                                         jQuery.map( scripts, restoreScript );
532                                         // Evaluate executable scripts on first document insertion
533                                         for ( i = 0; i < hasScripts; i++ ) {
534                                                 node = scripts[ i ];
535                                                 if ( rscriptType.test( node.type || "" ) &&
536                                                         !dataPriv.access( node, "globalEval" ) &&
537                                                         jQuery.contains( doc, node ) ) {
539                                                         if ( node.src ) {
540                                                                 // Optional AJAX dependency, but won't run scripts if not present
541                                                                 if ( jQuery._evalUrl ) {
542                                                                         jQuery._evalUrl( node.src );
543                                                                 }
544                                                         } else {
545                                                                 jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
546                                                         }
547                                                 }
548                                         }
549                                 }
550                         }
551                 }
553                 return this;
554         }
557 jQuery.each({
558         appendTo: "append",
559         prependTo: "prepend",
560         insertBefore: "before",
561         insertAfter: "after",
562         replaceAll: "replaceWith"
563 }, function( name, original ) {
564         jQuery.fn[ name ] = function( selector ) {
565                 var elems,
566                         ret = [],
567                         insert = jQuery( selector ),
568                         last = insert.length - 1,
569                         i = 0;
571                 for ( ; i <= last; i++ ) {
572                         elems = i === last ? this : this.clone( true );
573                         jQuery( insert[ i ] )[ original ]( elems );
575                         // Support: Android<4.1, PhantomJS<2
576                         // .get() because push.apply(_, arraylike) throws on ancient WebKit
577                         push.apply( ret, elems.get() );
578                 }
580                 return this.pushStack( ret );
581         };
584 return jQuery;