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