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