Offset: allow offset setter to throw for disconnected elements
[jquery.git] / src / manipulation.js
blobd085755a35fa60196c3fc6cdfe3c01f3e452da73
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         htmlPrefilter: function( html ) {
163                 return html.replace( rxhtmlTag, "<$1></$2>" );
164         },
166         clone: function( elem, dataAndEvents, deepDataAndEvents ) {
167                 var i, l, srcElements, destElements,
168                         clone = elem.cloneNode( true ),
169                         inPage = jQuery.contains( elem.ownerDocument, elem );
171                 // Fix IE cloning issues
172                 if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
173                                 !jQuery.isXMLDoc( elem ) ) {
175                         // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
176                         destElements = getAll( clone );
177                         srcElements = getAll( elem );
179                         for ( i = 0, l = srcElements.length; i < l; i++ ) {
180                                 fixInput( srcElements[ i ], destElements[ i ] );
181                         }
182                 }
184                 // Copy the events from the original to the clone
185                 if ( dataAndEvents ) {
186                         if ( deepDataAndEvents ) {
187                                 srcElements = srcElements || getAll( elem );
188                                 destElements = destElements || getAll( clone );
190                                 for ( i = 0, l = srcElements.length; i < l; i++ ) {
191                                         cloneCopyEvent( srcElements[ i ], destElements[ i ] );
192                                 }
193                         } else {
194                                 cloneCopyEvent( elem, clone );
195                         }
196                 }
198                 // Preserve script evaluation history
199                 destElements = getAll( clone, "script" );
200                 if ( destElements.length > 0 ) {
201                         setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
202                 }
204                 // Return the cloned set
205                 return clone;
206         },
208         buildFragment: function( elems, context, scripts, selection, ignored ) {
209                 var elem, tmp, tag, wrap, contains, j,
210                         fragment = context.createDocumentFragment(),
211                         nodes = [],
212                         i = 0,
213                         l = elems.length;
215                 for ( ; i < l; i++ ) {
216                         elem = elems[ i ];
218                         if ( elem || elem === 0 ) {
220                                 // Add nodes directly
221                                 if ( jQuery.type( elem ) === "object" ) {
222                                         // Support: Android<4.1, PhantomJS<2
223                                         // push.apply(_, arraylike) throws on ancient WebKit
224                                         jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
226                                 // Convert non-html into a text node
227                                 } else if ( !rhtml.test( elem ) ) {
228                                         nodes.push( context.createTextNode( elem ) );
230                                 // Convert html into DOM nodes
231                                 } else {
232                                         tmp = tmp || fragment.appendChild( context.createElement("div") );
234                                         // Deserialize a standard representation
235                                         tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
236                                         wrap = wrapMap[ tag ] || wrapMap._default;
237                                         tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];
239                                         // Descend through wrappers to the right content
240                                         j = wrap[ 0 ];
241                                         while ( j-- ) {
242                                                 tmp = tmp.lastChild;
243                                         }
245                                         // Support: Android<4.1, PhantomJS<2
246                                         // push.apply(_, arraylike) throws on ancient WebKit
247                                         jQuery.merge( nodes, tmp.childNodes );
249                                         // Remember the top-level container
250                                         tmp = fragment.firstChild;
252                                         // Ensure the created nodes are orphaned (#12392)
253                                         tmp.textContent = "";
254                                 }
255                         }
256                 }
258                 // Remove wrapper from fragment
259                 fragment.textContent = "";
261                 i = 0;
262                 while ( (elem = nodes[ i++ ]) ) {
264                         // Skip elements already in the context collection (trac-4087)
265                         if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
266                                 if ( ignored ) {
267                                         ignored.push( elem );
268                                 }
269                                 continue;
270                         }
272                         contains = jQuery.contains( elem.ownerDocument, elem );
274                         // Append to fragment
275                         tmp = getAll( fragment.appendChild( elem ), "script" );
277                         // Preserve script evaluation history
278                         if ( contains ) {
279                                 setGlobalEval( tmp );
280                         }
282                         // Capture executables
283                         if ( scripts ) {
284                                 j = 0;
285                                 while ( (elem = tmp[ j++ ]) ) {
286                                         if ( rscriptType.test( elem.type || "" ) ) {
287                                                 scripts.push( elem );
288                                         }
289                                 }
290                         }
291                 }
293                 return fragment;
294         },
296         cleanData: function( elems ) {
297                 var data, elem, type,
298                         special = jQuery.event.special,
299                         i = 0;
301                 for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
302                         if ( jQuery.acceptData( elem ) && (data = elem[ dataPriv.expando ])) {
303                                 if ( data.events ) {
304                                         for ( type in data.events ) {
305                                                 if ( special[ type ] ) {
306                                                         jQuery.event.remove( elem, type );
308                                                 // This is a shortcut to avoid jQuery.event.remove's overhead
309                                                 } else {
310                                                         jQuery.removeEvent( elem, type, data.handle );
311                                                 }
312                                         }
313                                 }
314                                 delete elem[ dataPriv.expando ];
315                         }
316                 }
317         }
320 jQuery.fn.extend({
321         text: function( value ) {
322                 return access( this, function( value ) {
323                         return value === undefined ?
324                                 jQuery.text( this ) :
325                                 this.empty().each(function() {
326                                         if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
327                                                 this.textContent = value;
328                                         }
329                                 });
330                 }, null, value, arguments.length );
331         },
333         append: function() {
334                 return this.domManip( arguments, function( elem ) {
335                         if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
336                                 var target = manipulationTarget( this, elem );
337                                 target.appendChild( elem );
338                         }
339                 });
340         },
342         prepend: function() {
343                 return this.domManip( arguments, function( elem ) {
344                         if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
345                                 var target = manipulationTarget( this, elem );
346                                 target.insertBefore( elem, target.firstChild );
347                         }
348                 });
349         },
351         before: function() {
352                 return this.domManip( arguments, function( elem ) {
353                         if ( this.parentNode ) {
354                                 this.parentNode.insertBefore( elem, this );
355                         }
356                 });
357         },
359         after: function() {
360                 return this.domManip( arguments, function( elem ) {
361                         if ( this.parentNode ) {
362                                 this.parentNode.insertBefore( elem, this.nextSibling );
363                         }
364                 });
365         },
367         remove: function( selector, keepData /* Internal Use Only */ ) {
368                 var elem,
369                         elems = selector ? jQuery.filter( selector, this ) : this,
370                         i = 0;
372                 for ( ; (elem = elems[i]) != null; i++ ) {
373                         if ( !keepData && elem.nodeType === 1 ) {
374                                 jQuery.cleanData( getAll( elem ) );
375                         }
377                         if ( elem.parentNode ) {
378                                 if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
379                                         setGlobalEval( getAll( elem, "script" ) );
380                                 }
381                                 elem.parentNode.removeChild( elem );
382                         }
383                 }
385                 return this;
386         },
388         empty: function() {
389                 var elem,
390                         i = 0;
392                 for ( ; (elem = this[i]) != null; i++ ) {
393                         if ( elem.nodeType === 1 ) {
395                                 // Prevent memory leaks
396                                 jQuery.cleanData( getAll( elem, false ) );
398                                 // Remove any remaining nodes
399                                 elem.textContent = "";
400                         }
401                 }
403                 return this;
404         },
406         clone: function( dataAndEvents, deepDataAndEvents ) {
407                 dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
408                 deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
410                 return this.map(function() {
411                         return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
412                 });
413         },
415         html: function( value ) {
416                 return access( this, function( value ) {
417                         var elem = this[ 0 ] || {},
418                                 i = 0,
419                                 l = this.length;
421                         if ( value === undefined && elem.nodeType === 1 ) {
422                                 return elem.innerHTML;
423                         }
425                         // See if we can take a shortcut and just use innerHTML
426                         if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
427                                 !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
429                                 value = jQuery.htmlPrefilter( value );
431                                 try {
432                                         for ( ; i < l; i++ ) {
433                                                 elem = this[ i ] || {};
435                                                 // Remove element nodes and prevent memory leaks
436                                                 if ( elem.nodeType === 1 ) {
437                                                         jQuery.cleanData( getAll( elem, false ) );
438                                                         elem.innerHTML = value;
439                                                 }
440                                         }
442                                         elem = 0;
444                                 // If using innerHTML throws an exception, use the fallback method
445                                 } catch ( e ) {}
446                         }
448                         if ( elem ) {
449                                 this.empty().append( value );
450                         }
451                 }, null, value, arguments.length );
452         },
454         replaceWith: function() {
455                 var ignored = [];
457                 // Make the changes, replacing each non-ignored context element with the new content
458                 return this.domManip( arguments, function( elem ) {
459                         var parent = this.parentNode;
461                         if ( jQuery.inArray( this, ignored ) < 0 ) {
462                                 jQuery.cleanData( getAll( this ) );
463                                 if ( parent ) {
464                                         parent.replaceChild( elem, this );
465                                 }
466                         }
468                 // Force callback invocation
469                 }, ignored );
470         },
472         detach: function( selector ) {
473                 return this.remove( selector, true );
474         },
476         domManip: function( args, callback, ignored ) {
478                 // Flatten any nested arrays
479                 args = concat.apply( [], args );
481                 var fragment, first, scripts, hasScripts, node, doc,
482                         i = 0,
483                         l = this.length,
484                         set = this,
485                         iNoClone = l - 1,
486                         value = args[ 0 ],
487                         isFunction = jQuery.isFunction( value );
489                 // We can't cloneNode fragments that contain checked, in WebKit
490                 if ( isFunction ||
491                                 ( l > 1 && typeof value === "string" &&
492                                         !support.checkClone && rchecked.test( value ) ) ) {
493                         return this.each(function( index ) {
494                                 var self = set.eq( index );
495                                 if ( isFunction ) {
496                                         args[ 0 ] = value.call( this, index, self.html() );
497                                 }
498                                 self.domManip( args, callback, ignored );
499                         });
500                 }
502                 if ( l ) {
503                         fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this, ignored );
504                         first = fragment.firstChild;
506                         if ( fragment.childNodes.length === 1 ) {
507                                 fragment = first;
508                         }
510                         // Require either new content or an interest in ignored elements to invoke the callback
511                         if ( first || ignored ) {
512                                 scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
513                                 hasScripts = scripts.length;
515                                 // Use the original fragment for the last item
516                                 // instead of the first because it can end up
517                                 // being emptied incorrectly in certain situations (#8070).
518                                 for ( ; i < l; i++ ) {
519                                         node = fragment;
521                                         if ( i !== iNoClone ) {
522                                                 node = jQuery.clone( node, true, true );
524                                                 // Keep references to cloned scripts for later restoration
525                                                 if ( hasScripts ) {
526                                                         // Support: Android<4.1, PhantomJS<2
527                                                         // push.apply(_, arraylike) throws on ancient WebKit
528                                                         jQuery.merge( scripts, getAll( node, "script" ) );
529                                                 }
530                                         }
532                                         callback.call( this[ i ], node, i );
533                                 }
535                                 if ( hasScripts ) {
536                                         doc = scripts[ scripts.length - 1 ].ownerDocument;
538                                         // Reenable scripts
539                                         jQuery.map( scripts, restoreScript );
541                                         // Evaluate executable scripts on first document insertion
542                                         for ( i = 0; i < hasScripts; i++ ) {
543                                                 node = scripts[ i ];
544                                                 if ( rscriptType.test( node.type || "" ) &&
545                                                         !dataPriv.access( node, "globalEval" ) &&
546                                                         jQuery.contains( doc, node ) ) {
548                                                         if ( node.src ) {
549                                                                 // Optional AJAX dependency, but won't run scripts if not present
550                                                                 if ( jQuery._evalUrl ) {
551                                                                         jQuery._evalUrl( node.src );
552                                                                 }
553                                                         } else {
554                                                                 jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
555                                                         }
556                                                 }
557                                         }
558                                 }
559                         }
560                 }
562                 return this;
563         }
566 jQuery.each({
567         appendTo: "append",
568         prependTo: "prepend",
569         insertBefore: "before",
570         insertAfter: "after",
571         replaceAll: "replaceWith"
572 }, function( name, original ) {
573         jQuery.fn[ name ] = function( selector ) {
574                 var elems,
575                         ret = [],
576                         insert = jQuery( selector ),
577                         last = insert.length - 1,
578                         i = 0;
580                 for ( ; i <= last; i++ ) {
581                         elems = i === last ? this : this.clone( true );
582                         jQuery( insert[ i ] )[ original ]( elems );
584                         // Support: Android<4.1, PhantomJS<2
585                         // .get() because push.apply(_, arraylike) throws on ancient WebKit
586                         push.apply( ret, elems.get() );
587                 }
589                 return this.pushStack( ret );
590         };
593 return jQuery;