Make sure that XHTML-style HTML is purified in .html(). Fixes #5845.
[jquery.git] / src / manipulation.js
1 var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
2         rleadingWhitespace = /^\s+/,
3         rxhtmlTag = /(<([\w:]+)[^>]*?)\/>/g,
4         rselfClosing = /^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,
5         rtagName = /<([\w:]+)/,
6         rtbody = /<tbody/i,
7         rhtml = /<|&\w+;/,
8         fcloseTag = function( all, front, tag ) {
9                 return rselfClosing.test( tag ) ?
10                         all :
11                         front + "></" + tag + ">";
12         },
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                                 return self.text( text.call(this, i, self.text()) );
39                         });
40                 }
41
42                 if ( typeof text !== "object" && text !== undefined ) {
43                         return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
44                 }
45
46                 return jQuery.getText( this );
47         },
48
49         wrapAll: function( html ) {
50                 if ( jQuery.isFunction( html ) ) {
51                         return this.each(function(i) {
52                                 jQuery(this).wrapAll( html.call(this, i) );
53                         });
54                 }
55
56                 if ( this[0] ) {
57                         // The elements to wrap the target around
58                         var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
59
60                         if ( this[0].parentNode ) {
61                                 wrap.insertBefore( this[0] );
62                         }
63
64                         wrap.map(function() {
65                                 var elem = this;
66
67                                 while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
68                                         elem = elem.firstChild;
69                                 }
70
71                                 return elem;
72                         }).append(this);
73                 }
74
75                 return this;
76         },
77
78         wrapInner: function( html ) {
79                 return this.each(function() {
80                         var self = jQuery( this ), contents = self.contents();
81
82                         if ( contents.length ) {
83                                 contents.wrapAll( html );
84
85                         } else {
86                                 self.append( html );
87                         }
88                 });
89         },
90
91         wrap: function( html ) {
92                 return this.each(function() {
93                         jQuery( this ).wrapAll( html );
94                 });
95         },
96
97         unwrap: function() {
98                 return this.parent().each(function() {
99                         if ( !jQuery.nodeName( this, "body" ) ) {
100                                 jQuery( this ).replaceWith( this.childNodes );
101                         }
102                 }).end();
103         },
104
105         append: function() {
106                 return this.domManip(arguments, true, function( elem ) {
107                         if ( this.nodeType === 1 ) {
108                                 this.appendChild( elem );
109                         }
110                 });
111         },
112
113         prepend: function() {
114                 return this.domManip(arguments, true, function( elem ) {
115                         if ( this.nodeType === 1 ) {
116                                 this.insertBefore( elem, this.firstChild );
117                         }
118                 });
119         },
120
121         before: function() {
122                 if ( this[0] && this[0].parentNode ) {
123                         return this.domManip(arguments, false, function( elem ) {
124                                 this.parentNode.insertBefore( elem, this );
125                         });
126                 } else if ( arguments.length ) {
127                         var set = jQuery(arguments[0]);
128                         set.push.apply( set, this.toArray() );
129                         return this.pushStack( set, "before", arguments );
130                 }
131         },
132
133         after: function() {
134                 if ( this[0] && this[0].parentNode ) {
135                         return this.domManip(arguments, false, function( elem ) {
136                                 this.parentNode.insertBefore( elem, this.nextSibling );
137                         });
138                 } else if ( arguments.length ) {
139                         var set = this.pushStack( this, "after", arguments );
140                         set.push.apply( set, jQuery(arguments[0]).toArray() );
141                         return set;
142                 }
143         },
144
145         clone: function( events ) {
146                 // Do the clone
147                 var ret = this.map(function() {
148                         if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
149                                 // IE copies events bound via attachEvent when
150                                 // using cloneNode. Calling detachEvent on the
151                                 // clone will also remove the events from the orignal
152                                 // In order to get around this, we use innerHTML.
153                                 // Unfortunately, this means some modifications to
154                                 // attributes in IE that are actually only stored
155                                 // as properties will not be copied (such as the
156                                 // the name attribute on an input).
157                                 var html = this.outerHTML, ownerDocument = this.ownerDocument;
158                                 if ( !html ) {
159                                         var div = ownerDocument.createElement("div");
160                                         div.appendChild( this.cloneNode(true) );
161                                         html = div.innerHTML;
162                                 }
163
164                                 return jQuery.clean([html.replace(rinlinejQuery, "")
165                                         .replace(rleadingWhitespace, "")], ownerDocument)[0];
166                         } else {
167                                 return this.cloneNode(true);
168                         }
169                 });
170
171                 // Copy the events from the original to the clone
172                 if ( events === true ) {
173                         cloneCopyEvent( this, ret );
174                         cloneCopyEvent( this.find("*"), ret.find("*") );
175                 }
176
177                 // Return the cloned set
178                 return ret;
179         },
180
181         html: function( value ) {
182                 if ( value === undefined ) {
183                         return this[0] && this[0].nodeType === 1 ?
184                                 this[0].innerHTML.replace(rinlinejQuery, "") :
185                                 null;
186
187                 // See if we can take a shortcut and just use innerHTML
188                 } else if ( typeof value === "string" && !/<script/i.test( value ) &&
189                         (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
190                         !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
191
192                         value = value.replace(rxhtmlTag, fcloseTag);
193
194                         try {
195                                 for ( var i = 0, l = this.length; i < l; i++ ) {
196                                         // Remove element nodes and prevent memory leaks
197                                         if ( this[i].nodeType === 1 ) {
198                                                 jQuery.cleanData( this[i].getElementsByTagName("*") );
199                                                 this[i].innerHTML = value;
200                                         }
201                                 }
202
203                         // If using innerHTML throws an exception, use the fallback method
204                         } catch(e) {
205                                 this.empty().append( value );
206                         }
207
208                 } else if ( jQuery.isFunction( value ) ) {
209                         this.each(function(i){
210                                 var self = jQuery(this), old = self.html();
211                                 self.empty().append(function(){
212                                         return value.call( this, i, old );
213                                 });
214                         });
215
216                 } else {
217                         this.empty().append( value );
218                 }
219
220                 return this;
221         },
222
223         replaceWith: function( value ) {
224                 if ( this[0] && this[0].parentNode ) {
225                         // Make sure that the elements are removed from the DOM before they are inserted
226                         // this can help fix replacing a parent with child elements
227                         if ( !jQuery.isFunction( value ) ) {
228                                 value = jQuery( value ).detach();
229                         }
230
231                         return this.each(function() {
232                                 var next = this.nextSibling, parent = this.parentNode;
233
234                                 jQuery(this).remove();
235
236                                 if ( next ) {
237                                         jQuery(next).before( value );
238                                 } else {
239                                         jQuery(parent).append( value );
240                                 }
241                         });
242                 } else {
243                         return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
244                 }
245         },
246
247         detach: function( selector ) {
248                 return this.remove( selector, true );
249         },
250
251         domManip: function( args, table, callback ) {
252                 var results, first, value = args[0], scripts = [];
253
254                 if ( jQuery.isFunction(value) ) {
255                         return this.each(function(i) {
256                                 var self = jQuery(this);
257                                 args[0] = value.call(this, i, table ? self.html() : undefined);
258                                 return self.domManip( args, table, callback );
259                         });
260                 }
261
262                 if ( this[0] ) {
263                         // If we're in a fragment, just use that instead of building a new one
264                         if ( args[0] && args[0].parentNode && args[0].parentNode.nodeType === 11 ) {
265                                 results = { fragment: args[0].parentNode };
266                         } else {
267                                 results = buildFragment( args, this, scripts );
268                         }
269
270                         first = results.fragment.firstChild;
271
272                         if ( first ) {
273                                 table = table && jQuery.nodeName( first, "tr" );
274
275                                 for ( var i = 0, l = this.length; i < l; i++ ) {
276                                         callback.call(
277                                                 table ?
278                                                         root(this[i], first) :
279                                                         this[i],
280                                                 results.cacheable || this.length > 1 || i > 0 ?
281                                                         results.fragment.cloneNode(true) :
282                                                         results.fragment
283                                         );
284                                 }
285                         }
286
287                         if ( scripts ) {
288                                 jQuery.each( scripts, evalScript );
289                         }
290                 }
291
292                 return this;
293
294                 function root( elem, cur ) {
295                         return jQuery.nodeName(elem, "table") ?
296                                 (elem.getElementsByTagName("tbody")[0] ||
297                                 elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
298                                 elem;
299                 }
300         }
301 });
302
303 function cloneCopyEvent(orig, ret) {
304         var i = 0;
305
306         ret.each(function() {
307                 if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) {
308                         return;
309                 }
310
311                 var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events;
312
313                 if ( events ) {
314                         delete curData.handle;
315                         curData.events = {};
316
317                         for ( var type in events ) {
318                                 for ( var handler in events[ type ] ) {
319                                         jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
320                                 }
321                         }
322                 }
323         });
324 }
325
326 function buildFragment( args, nodes, scripts ) {
327         var fragment, cacheable, cacheresults, doc;
328
329         if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && args[0].indexOf("<option") < 0 ) {
330                 cacheable = true;
331                 cacheresults = jQuery.fragments[ args[0] ];
332                 if ( cacheresults ) {
333                         if ( cacheresults !== 1 ) {
334                                 fragment = cacheresults;
335                         }
336                 }
337         }
338
339         if ( !fragment ) {
340                 doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
341                 fragment = doc.createDocumentFragment();
342                 jQuery.clean( args, doc, fragment, scripts );
343         }
344
345         if ( cacheable ) {
346                 jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
347         }
348
349         return { fragment: fragment, cacheable: cacheable };
350 }
351
352 jQuery.fragments = {};
353
354 jQuery.each({
355         appendTo: "append",
356         prependTo: "prepend",
357         insertBefore: "before",
358         insertAfter: "after",
359         replaceAll: "replaceWith"
360 }, function( name, original ) {
361         jQuery.fn[ name ] = function( selector ) {
362                 var ret = [], insert = jQuery( selector );
363
364                 for ( var i = 0, l = insert.length; i < l; i++ ) {
365                         var elems = (i > 0 ? this.clone(true) : this).get();
366                         jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
367                         ret = ret.concat( elems );
368                 }
369                 return this.pushStack( ret, name, insert.selector );
370         };
371 });
372
373 jQuery.each({
374         // keepData is for internal use only--do not document
375         remove: function( selector, keepData ) {
376                 if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
377                         if ( !keepData && this.nodeType === 1 ) {
378                                 jQuery.cleanData( this.getElementsByTagName("*") );
379                                 jQuery.cleanData( [ this ] );
380                         }
381
382                         if ( this.parentNode ) {
383                                  this.parentNode.removeChild( this );
384                         }
385                 }
386         },
387
388         empty: function() {
389                 // Remove element nodes and prevent memory leaks
390                 if ( this.nodeType === 1 ) {
391                         jQuery.cleanData( this.getElementsByTagName("*") );
392                 }
393
394                 // Remove any remaining nodes
395                 while ( this.firstChild ) {
396                         this.removeChild( this.firstChild );
397                 }
398         }
399 }, function( name, fn ) {
400         jQuery.fn[ name ] = function() {
401                 return this.each( fn, arguments );
402         };
403 });
404
405 jQuery.extend({
406         clean: function( elems, context, fragment, scripts ) {
407                 context = context || document;
408
409                 // !context.createElement fails in IE with an error but returns typeof 'object'
410                 if ( typeof context.createElement === "undefined" ) {
411                         context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
412                 }
413
414                 var ret = [];
415
416                 jQuery.each(elems, function( i, elem ) {
417                         if ( typeof elem === "number" ) {
418                                 elem += "";
419                         }
420
421                         if ( !elem ) {
422                                 return;
423                         }
424
425                         // Convert html string into DOM nodes
426                         if ( typeof elem === "string" && !rhtml.test( elem ) ) {
427                                 elem = context.createTextNode( elem );
428
429                         } else if ( typeof elem === "string" ) {
430                                 // Fix "XHTML"-style tags in all browsers
431                                 elem = elem.replace(rxhtmlTag, fcloseTag);
432
433                                 // Trim whitespace, otherwise indexOf won't work as expected
434                                 var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
435                                         wrap = wrapMap[ tag ] || wrapMap._default,
436                                         depth = wrap[0],
437                                         div = context.createElement("div");
438
439                                 // Go to html and back, then peel off extra wrappers
440                                 div.innerHTML = wrap[1] + elem + wrap[2];
441
442                                 // Move to the right depth
443                                 while ( depth-- ) {
444                                         div = div.lastChild;
445                                 }
446
447                                 // Remove IE's autoinserted <tbody> from table fragments
448                                 if ( !jQuery.support.tbody ) {
449
450                                         // String was a <table>, *may* have spurious <tbody>
451                                         var hasBody = rtbody.test(elem),
452                                                 tbody = tag === "table" && !hasBody ?
453                                                         div.firstChild && div.firstChild.childNodes :
454
455                                                         // String was a bare <thead> or <tfoot>
456                                                         wrap[1] === "<table>" && !hasBody ?
457                                                                 div.childNodes :
458                                                                 [];
459
460                                         for ( var j = tbody.length - 1; j >= 0 ; --j ) {
461                                                 if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
462                                                         tbody[ j ].parentNode.removeChild( tbody[ j ] );
463                                                 }
464                                         }
465
466                                 }
467
468                                 // IE completely kills leading whitespace when innerHTML is used
469                                 if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
470                                         div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
471                                 }
472
473                                 elem = jQuery.makeArray( div.childNodes );
474                         }
475
476                         if ( elem.nodeType ) {
477                                 ret.push( elem );
478                         } else {
479                                 ret = jQuery.merge( ret, elem );
480                         }
481
482                 });
483
484                 if ( fragment ) {
485                         for ( var i = 0; ret[i]; i++ ) {
486                                 if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
487                                         scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
488                                 } else {
489                                         if ( ret[i].nodeType === 1 ) {
490                                                 ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
491                                         }
492                                         fragment.appendChild( ret[i] );
493                                 }
494                         }
495                 }
496
497                 return ret;
498         },
499         
500         cleanData: function( elems ) {
501                 for ( var i = 0, elem, id; (elem = elems[i]) != null; i++ ) {
502                         jQuery.event.remove( elem );
503                         jQuery.removeData( elem );
504                 }
505         }
506 });