Data: move element cache to element[expando]
[jquery.git] / src / manipulation.js
blobbe982dc2dcfb07cd363b8665d8920e6b05e5874d
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>" ],
37                 // Some of the following wrappers are not fully defined, because
38                 // their parent elements (except for "table" element) could be omitted
39                 // since browser parsers are smart enough to auto-insert them
41                 // Support: Android 2.3
42                 // Android browser doesn't auto-insert colgroup
43                 col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
45                 // Auto-insert "tbody" element
46                 tr: [ 2, "<table>", "</table>" ],
48                 // Auto-insert "tbody" and "tr" elements
49                 td: [ 3, "<table>", "</table>" ],
51                 _default: [ 0, "", "" ]
52         };
54 // Support: IE9
55 wrapMap.optgroup = wrapMap.option;
57 wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
58 wrapMap.th = wrapMap.td;
60 function manipulationTarget( elem, content ) {
61         if ( jQuery.nodeName( elem, "table" ) &&
62                 jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {
64                 return elem.getElementsByTagName( "tbody" )[ 0 ] || elem;
65         }
67         return elem;
70 // Replace/restore the type attribute of script elements for safe DOM manipulation
71 function disableScript( elem ) {
72         elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
73         return elem;
75 function restoreScript( elem ) {
76         var match = rscriptTypeMasked.exec( elem.type );
78         if ( match ) {
79                 elem.type = match[ 1 ];
80         } else {
81                 elem.removeAttribute("type");
82         }
84         return elem;
87 // Mark scripts as having already been evaluated
88 function setGlobalEval( elems, refElements ) {
89         var i = 0,
90                 l = elems.length;
92         for ( ; i < l; i++ ) {
93                 dataPriv.set(
94                         elems[ i ], "globalEval", !refElements || dataPriv.get( refElements[ i ], "globalEval" )
95                 );
96         }
99 function cloneCopyEvent( src, dest ) {
100         var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
102         if ( dest.nodeType !== 1 ) {
103                 return;
104         }
106         // 1. Copy private data: events, handlers, etc.
107         if ( dataPriv.hasData( src ) ) {
108                 pdataOld = dataPriv.access( src );
109                 pdataCur = dataPriv.set( dest, pdataOld );
110                 events = pdataOld.events;
112                 if ( events ) {
113                         delete pdataCur.handle;
114                         pdataCur.events = {};
116                         for ( type in events ) {
117                                 for ( i = 0, l = events[ type ].length; i < l; i++ ) {
118                                         jQuery.event.add( dest, type, events[ type ][ i ] );
119                                 }
120                         }
121                 }
122         }
124         // 2. Copy user data
125         if ( dataUser.hasData( src ) ) {
126                 udataOld = dataUser.access( src );
127                 udataCur = jQuery.extend( {}, udataOld );
129                 dataUser.set( dest, udataCur );
130         }
133 function getAll( context, tag ) {
134         // Support: IE9-11+
135         // Use typeof to avoid zero-argument method invocation on host objects (#15151)
136         var ret = typeof context.getElementsByTagName !== "undefined" ?
137                         context.getElementsByTagName( tag || "*" ) :
138                         typeof context.querySelectorAll !== "undefined" ?
139                                 context.querySelectorAll( tag || "*" ) :
140                         [];
142         return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
143                 jQuery.merge( [ context ], ret ) :
144                 ret;
147 // Fix IE bugs, see support tests
148 function fixInput( src, dest ) {
149         var nodeName = dest.nodeName.toLowerCase();
151         // Fails to persist the checked state of a cloned checkbox or radio button.
152         if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
153                 dest.checked = src.checked;
155         // Fails to return the selected option to the default selected state when cloning options
156         } else if ( nodeName === "input" || nodeName === "textarea" ) {
157                 dest.defaultValue = src.defaultValue;
158         }
161 jQuery.extend({
162         clone: function( elem, dataAndEvents, deepDataAndEvents ) {
163                 var i, l, srcElements, destElements,
164                         clone = elem.cloneNode( true ),
165                         inPage = jQuery.contains( elem.ownerDocument, elem );
167                 // Fix IE cloning issues
168                 if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
169                                 !jQuery.isXMLDoc( elem ) ) {
171                         // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
172                         destElements = getAll( clone );
173                         srcElements = getAll( elem );
175                         for ( i = 0, l = srcElements.length; i < l; i++ ) {
176                                 fixInput( srcElements[ i ], destElements[ i ] );
177                         }
178                 }
180                 // Copy the events from the original to the clone
181                 if ( dataAndEvents ) {
182                         if ( deepDataAndEvents ) {
183                                 srcElements = srcElements || getAll( elem );
184                                 destElements = destElements || getAll( clone );
186                                 for ( i = 0, l = srcElements.length; i < l; i++ ) {
187                                         cloneCopyEvent( srcElements[ i ], destElements[ i ] );
188                                 }
189                         } else {
190                                 cloneCopyEvent( elem, clone );
191                         }
192                 }
194                 // Preserve script evaluation history
195                 destElements = getAll( clone, "script" );
196                 if ( destElements.length > 0 ) {
197                         setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
198                 }
200                 // Return the cloned set
201                 return clone;
202         },
204         buildFragment: function( elems, context, scripts, selection ) {
205                 var elem, tmp, tag, wrap, contains, j,
206                         fragment = context.createDocumentFragment(),
207                         nodes = [],
208                         i = 0,
209                         l = elems.length;
211                 for ( ; i < l; i++ ) {
212                         elem = elems[ i ];
214                         if ( elem || elem === 0 ) {
216                                 // Add nodes directly
217                                 if ( jQuery.type( elem ) === "object" ) {
218                                         // Support: Android<4.1, PhantomJS<2
219                                         // push.apply(_, arraylike) throws on ancient WebKit
220                                         jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
222                                 // Convert non-html into a text node
223                                 } else if ( !rhtml.test( elem ) ) {
224                                         nodes.push( context.createTextNode( elem ) );
226                                 // Convert html into DOM nodes
227                                 } else {
228                                         tmp = tmp || fragment.appendChild( context.createElement("div") );
230                                         // Deserialize a standard representation
231                                         tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
232                                         wrap = wrapMap[ tag ] || wrapMap._default;
233                                         tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
235                                         // Descend through wrappers to the right content
236                                         j = wrap[ 0 ];
237                                         while ( j-- ) {
238                                                 tmp = tmp.lastChild;
239                                         }
241                                         // Support: Android<4.1, PhantomJS<2
242                                         // push.apply(_, arraylike) throws on ancient WebKit
243                                         jQuery.merge( nodes, tmp.childNodes );
245                                         // Remember the top-level container
246                                         tmp = fragment.firstChild;
248                                         // Ensure the created nodes are orphaned (#12392)
249                                         tmp.textContent = "";
250                                 }
251                         }
252                 }
254                 // Remove wrapper from fragment
255                 fragment.textContent = "";
257                 i = 0;
258                 while ( (elem = nodes[ i++ ]) ) {
260                         // #4087 - If origin and destination elements are the same, and this is
261                         // that element, do not do anything
262                         if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
263                                 continue;
264                         }
266                         contains = jQuery.contains( elem.ownerDocument, elem );
268                         // Append to fragment
269                         tmp = getAll( fragment.appendChild( elem ), "script" );
271                         // Preserve script evaluation history
272                         if ( contains ) {
273                                 setGlobalEval( tmp );
274                         }
276                         // Capture executables
277                         if ( scripts ) {
278                                 j = 0;
279                                 while ( (elem = tmp[ j++ ]) ) {
280                                         if ( rscriptType.test( elem.type || "" ) ) {
281                                                 scripts.push( elem );
282                                         }
283                                 }
284                         }
285                 }
287                 return fragment;
288         },
290         cleanData: function( elems ) {
291                 var data, elem, type,
292                         special = jQuery.event.special,
293                         i = 0;
295                 for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
296                         if ( jQuery.acceptData( elem ) && (data = elem[ dataPriv.expando ])) {
297                                 if ( data.events ) {
298                                         for ( type in data.events ) {
299                                                 if ( special[ type ] ) {
300                                                         jQuery.event.remove( elem, type );
302                                                 // This is a shortcut to avoid jQuery.event.remove's overhead
303                                                 } else {
304                                                         jQuery.removeEvent( elem, type, data.handle );
305                                                 }
306                                         }
307                                 }
308                                 delete data.events;
309                         }
310                 }
311         }
314 jQuery.fn.extend({
315         text: function( value ) {
316                 return access( this, function( value ) {
317                         return value === undefined ?
318                                 jQuery.text( this ) :
319                                 this.empty().each(function() {
320                                         if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
321                                                 this.textContent = value;
322                                         }
323                                 });
324                 }, null, value, arguments.length );
325         },
327         append: function() {
328                 return this.domManip( arguments, function( elem ) {
329                         if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
330                                 var target = manipulationTarget( this, elem );
331                                 target.appendChild( elem );
332                         }
333                 });
334         },
336         prepend: function() {
337                 return this.domManip( arguments, function( elem ) {
338                         if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
339                                 var target = manipulationTarget( this, elem );
340                                 target.insertBefore( elem, target.firstChild );
341                         }
342                 });
343         },
345         before: function() {
346                 return this.domManip( arguments, function( elem ) {
347                         if ( this.parentNode ) {
348                                 this.parentNode.insertBefore( elem, this );
349                         }
350                 });
351         },
353         after: function() {
354                 return this.domManip( arguments, function( elem ) {
355                         if ( this.parentNode ) {
356                                 this.parentNode.insertBefore( elem, this.nextSibling );
357                         }
358                 });
359         },
361         remove: function( selector, keepData /* Internal Use Only */ ) {
362                 var elem,
363                         elems = selector ? jQuery.filter( selector, this ) : this,
364                         i = 0;
366                 for ( ; (elem = elems[i]) != null; i++ ) {
367                         if ( !keepData && elem.nodeType === 1 ) {
368                                 jQuery.cleanData( getAll( elem ) );
369                         }
371                         if ( elem.parentNode ) {
372                                 if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
373                                         setGlobalEval( getAll( elem, "script" ) );
374                                 }
375                                 elem.parentNode.removeChild( elem );
376                         }
377                 }
379                 return this;
380         },
382         empty: function() {
383                 var elem,
384                         i = 0;
386                 for ( ; (elem = this[i]) != null; i++ ) {
387                         if ( elem.nodeType === 1 ) {
389                                 // Prevent memory leaks
390                                 jQuery.cleanData( getAll( elem, false ) );
392                                 // Remove any remaining nodes
393                                 elem.textContent = "";
394                         }
395                 }
397                 return this;
398         },
400         clone: function( dataAndEvents, deepDataAndEvents ) {
401                 dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
402                 deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
404                 return this.map(function() {
405                         return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
406                 });
407         },
409         html: function( value ) {
410                 return access( this, function( value ) {
411                         var elem = this[ 0 ] || {},
412                                 i = 0,
413                                 l = this.length;
415                         if ( value === undefined && elem.nodeType === 1 ) {
416                                 return elem.innerHTML;
417                         }
419                         // See if we can take a shortcut and just use innerHTML
420                         if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
421                                 !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
423                                 value = value.replace( rxhtmlTag, "<$1></$2>" );
425                                 try {
426                                         for ( ; i < l; i++ ) {
427                                                 elem = this[ i ] || {};
429                                                 // Remove element nodes and prevent memory leaks
430                                                 if ( elem.nodeType === 1 ) {
431                                                         jQuery.cleanData( getAll( elem, false ) );
432                                                         elem.innerHTML = value;
433                                                 }
434                                         }
436                                         elem = 0;
438                                 // If using innerHTML throws an exception, use the fallback method
439                                 } catch ( e ) {}
440                         }
442                         if ( elem ) {
443                                 this.empty().append( value );
444                         }
445                 }, null, value, arguments.length );
446         },
448         replaceWith: function() {
449                 var arg = arguments[ 0 ];
451                 // Make the changes, replacing each context element with the new content
452                 this.domManip( arguments, function( elem ) {
453                         arg = this.parentNode;
455                         jQuery.cleanData( getAll( this ) );
457                         if ( arg ) {
458                                 arg.replaceChild( elem, this );
459                         }
460                 });
462                 // Force removal if there was no new content (e.g., from empty arguments)
463                 return arg && (arg.length || arg.nodeType) ? this : this.remove();
464         },
466         detach: function( selector ) {
467                 return this.remove( selector, true );
468         },
470         domManip: function( args, callback ) {
472                 // Flatten any nested arrays
473                 args = concat.apply( [], args );
475                 var fragment, first, scripts, hasScripts, node, doc,
476                         i = 0,
477                         l = this.length,
478                         set = this,
479                         iNoClone = l - 1,
480                         value = args[ 0 ],
481                         isFunction = jQuery.isFunction( value );
483                 // We can't cloneNode fragments that contain checked, in WebKit
484                 if ( isFunction ||
485                                 ( l > 1 && typeof value === "string" &&
486                                         !support.checkClone && rchecked.test( value ) ) ) {
487                         return this.each(function( index ) {
488                                 var self = set.eq( index );
489                                 if ( isFunction ) {
490                                         args[ 0 ] = value.call( this, index, self.html() );
491                                 }
492                                 self.domManip( args, callback );
493                         });
494                 }
496                 if ( l ) {
497                         fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
498                         first = fragment.firstChild;
500                         if ( fragment.childNodes.length === 1 ) {
501                                 fragment = first;
502                         }
504                         if ( first ) {
505                                 scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
506                                 hasScripts = scripts.length;
508                                 // Use the original fragment for the last item
509                                 // instead of the first because it can end up
510                                 // being emptied incorrectly in certain situations (#8070).
511                                 for ( ; i < l; i++ ) {
512                                         node = fragment;
514                                         if ( i !== iNoClone ) {
515                                                 node = jQuery.clone( node, true, true );
517                                                 // Keep references to cloned scripts for later restoration
518                                                 if ( hasScripts ) {
519                                                         // Support: Android<4.1, PhantomJS<2
520                                                         // push.apply(_, arraylike) throws on ancient WebKit
521                                                         jQuery.merge( scripts, getAll( node, "script" ) );
522                                                 }
523                                         }
525                                         callback.call( this[ i ], node, i );
526                                 }
528                                 if ( hasScripts ) {
529                                         doc = scripts[ scripts.length - 1 ].ownerDocument;
531                                         // Reenable scripts
532                                         jQuery.map( scripts, restoreScript );
534                                         // Evaluate executable scripts on first document insertion
535                                         for ( i = 0; i < hasScripts; i++ ) {
536                                                 node = scripts[ i ];
537                                                 if ( rscriptType.test( node.type || "" ) &&
538                                                         !dataPriv.access( node, "globalEval" ) &&
539                                                         jQuery.contains( doc, node ) ) {
541                                                         if ( node.src ) {
542                                                                 // Optional AJAX dependency, but won't run scripts if not present
543                                                                 if ( jQuery._evalUrl ) {
544                                                                         jQuery._evalUrl( node.src );
545                                                                 }
546                                                         } else {
547                                                                 jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
548                                                         }
549                                                 }
550                                         }
551                                 }
552                         }
553                 }
555                 return this;
556         }
559 jQuery.each({
560         appendTo: "append",
561         prependTo: "prepend",
562         insertBefore: "before",
563         insertAfter: "after",
564         replaceAll: "replaceWith"
565 }, function( name, original ) {
566         jQuery.fn[ name ] = function( selector ) {
567                 var elems,
568                         ret = [],
569                         insert = jQuery( selector ),
570                         last = insert.length - 1,
571                         i = 0;
573                 for ( ; i <= last; i++ ) {
574                         elems = i === last ? this : this.clone( true );
575                         jQuery( insert[ i ] )[ original ]( elems );
577                         // Support: Android<4.1, PhantomJS<2
578                         // .get() because push.apply(_, arraylike) throws on ancient WebKit
579                         push.apply( ret, elems.get() );
580                 }
582                 return this.pushStack( ret );
583         };
586 return jQuery;