A follow-up to [6578] (which stopped adding expandos to elements that didn't have...
[jquery.git] / src / manipulation.js
index c537c70..547acc1 100644 (file)
@@ -1,16 +1,48 @@
+var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
+       rleadingWhitespace = /^\s+/,
+       rxhtmlTag = /(<(\w+)[^>]*?)\/>/g,
+       rselfClosing = /^(?:abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i,
+       rtagName = /<(\w+)/,
+       rtbody = /<tbody/i,
+       rhtml = /</,
+       fcloseTag = function(all, front, tag){
+               return rselfClosing.test(tag) ?
+                       all :
+                       front + "></" + tag + ">";
+       },
+       wrapMap = {
+               option: [ 1, "<select multiple='multiple'>", "</select>" ],
+               legend: [ 1, "<fieldset>", "</fieldset>" ],
+               thead: [ 1, "<table>", "</table>" ],
+               tr: [ 2, "<table><tbody>", "</tbody></table>" ],
+               td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
+               col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
+               _default: [ 0, "", "" ]
+       };
+
+wrapMap.optgroup = wrapMap.option;
+wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
+wrapMap.th = wrapMap.td;
+
+// IE can't serialize <link> and <script> tags normally
+if ( !jQuery.support.htmlSerialize ) {
+       wrapMap._default = [ 1, "div<div>", "</div>" ];
+}
+
 jQuery.fn.extend({
        text: function( text ) {
-               if ( typeof text !== "object" && text != null )
+               if ( typeof text !== "object" && text !== undefined )
                        return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
 
                var ret = "";
 
                jQuery.each( text || this, function(){
                        jQuery.each( this.childNodes, function(){
-                               if ( this.nodeType != 8 )
-                                       ret += this.nodeType != 1 ?
+                               if ( this.nodeType !== 8 ) {
+                                       ret += this.nodeType !== 1 ?
                                                this.nodeValue :
                                                jQuery.fn.text( [ this ] );
+                               }
                        });
                });
 
@@ -18,18 +50,26 @@ jQuery.fn.extend({
        },
 
        wrapAll: function( html ) {
+               if ( jQuery.isFunction( html ) ) {
+                       return this.each(function() {
+                               jQuery(this).wrapAll( html.apply(this, arguments) );
+                       });
+               }
+
                if ( this[0] ) {
                        // The elements to wrap the target around
-                       var wrap = jQuery( html, this[0].ownerDocument ).clone();
+                       var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone();
 
-                       if ( this[0].parentNode )
+                       if ( this[0].parentNode ) {
                                wrap.insertBefore( this[0] );
+                       }
 
                        wrap.map(function(){
                                var elem = this;
 
-                               while ( elem.firstChild )
+                               while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
                                        elem = elem.firstChild;
+                               }
 
                                return elem;
                        }).append(this);
@@ -52,28 +92,42 @@ jQuery.fn.extend({
 
        append: function() {
                return this.domManip(arguments, true, function(elem){
-                       if (this.nodeType == 1)
+                       if ( this.nodeType === 1 ) {
                                this.appendChild( elem );
+                       }
                });
        },
 
        prepend: function() {
                return this.domManip(arguments, true, function(elem){
-                       if (this.nodeType == 1)
+                       if ( this.nodeType === 1 ) {
                                this.insertBefore( elem, this.firstChild );
+                       }
                });
        },
 
        before: function() {
-               return this.domManip(arguments, false, function(elem){
-                       this.parentNode.insertBefore( elem, this );
-               });
+               if ( this[0] && this[0].parentNode ) {
+                       return this.domManip(arguments, false, function(elem){
+                               this.parentNode.insertBefore( elem, this );
+                       });
+               } else if ( arguments.length ) {
+                       var set = jQuery(arguments[0]);
+                       set.push.apply( set, this.toArray() );
+                       return this.pushStack( set, "before", arguments );
+               }
        },
 
        after: function() {
-               return this.domManip(arguments, false, function(elem){
-                       this.parentNode.insertBefore( elem, this.nextSibling );
-               });
+               if ( this[0] && this[0].parentNode ) {
+                       return this.domManip(arguments, false, function(elem){
+                               this.parentNode.insertBefore( elem, this.nextSibling );
+                       });
+               } else if ( arguments.length ) {
+                       var set = this.pushStack( this, "after", arguments );
+                       set.push.apply( set, jQuery(arguments[0]).toArray() );
+                       return set;
+               }
        },
 
        clone: function( events ) {
@@ -95,9 +149,11 @@ jQuery.fn.extend({
                                        html = div.innerHTML;
                                }
 
-                               return jQuery.clean([html.replace(/ jQuery\d+="(?:\d+|null)"/g, "").replace(/^\s*/, "")], ownerDocument)[0];
-                       } else
+                               return jQuery.clean([html.replace(rinlinejQuery, "")
+                                       .replace(rleadingWhitespace, "")], ownerDocument)[0];
+                       } else {
                                return this.cloneNode(true);
+                       }
                });
 
                // Copy the events from the original to the clone
@@ -105,8 +161,7 @@ jQuery.fn.extend({
                        var orig = this.find("*").andSelf(), i = 0;
 
                        ret.find("*").andSelf().each(function(){
-                               if ( this.nodeName !== orig[i].nodeName )
-                                       return;
+                               if ( this.nodeName !== orig[i].nodeName ) { return; }
 
                                var events = jQuery.data( orig[i], "events" );
 
@@ -125,36 +180,93 @@ jQuery.fn.extend({
        },
 
        html: function( value ) {
-               return value === undefined ?
-                       (this[0] ?
-                               this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g, "") :
-                               null) :
+               if ( value === undefined ) {
+                       return this[0] ?
+                               this[0].innerHTML.replace(rinlinejQuery, "") :
+                               null;
+
+               // See if we can take a shortcut and just use innerHTML
+               } else if ( typeof value === "string" && !/<script/i.test( value ) &&
+                       (!jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
+                       !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
+
+                       try {
+                               for ( var i = 0, l = this.length; i < l; i++ ) {
+                                       // Remove element nodes and prevent memory leaks
+                                       if ( this[i].nodeType === 1 ) {
+                                               cleanData( this[i].getElementsByTagName("*") );
+                                               this[i].innerHTML = value;
+                                       }
+                               }
+
+                       // If using innerHTML throws an exception, use the fallback method
+                       } catch(e) {
+                               this.empty().append( value );
+                       }
+
+               } else {
                        this.empty().append( value );
+               }
+
+               return this;
        },
 
        replaceWith: function( value ) {
-               return this.after( value ).remove();
+               if ( this[0] && this[0].parentNode ) {
+                       return this.after( value ).remove();
+               } else {
+                       return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
+               }
+       },
+
+       detach: function( selector ) {
+               return this.remove( selector, true );
        },
 
        domManip: function( args, table, callback ) {
+               var results, first, value = args[0], scripts = [];
+
+               if ( jQuery.isFunction(value) ) {
+                       return this.each(function() {
+                               args[0] = value.call(this);
+                               return jQuery(this).domManip( args, table, callback );
+                       });
+               }
+
                if ( this[0] ) {
-                       var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(),
-                               scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ),
-                               first = fragment.firstChild;
+                       // If we're in a fragment, just use that instead of building a new one
+                       if ( args[0] && args[0].parentNode && args[0].parentNode.nodeType === 11 ) {
+                               results = { fragment: args[0].parentNode };
+                       } else {
+                               results = buildFragment( args, this, scripts );
+                       }
 
-                       if ( first )
-                               for ( var i = 0, l = this.length; i < l; i++ )
-                                       callback.call( root(this[i], first), this.length > 1 || i > 0 ?
-                                                       fragment.cloneNode(true) : fragment );
+                       first = results.fragment.firstChild;
 
-                       if ( scripts )
+                       if ( first ) {
+                               table = table && jQuery.nodeName( first, "tr" );
+
+                               for ( var i = 0, l = this.length; i < l; i++ ) {
+                                       callback.call(
+                                               table ?
+                                                       root(this[i], first) :
+                                                       this[i],
+                                               results.cacheable || this.length > 1 || i > 0 ?
+                                                       results.fragment.cloneNode(true) :
+                                                       results.fragment
+                                       );
+                               }
+                       }
+
+                       if ( scripts ) {
                                jQuery.each( scripts, evalScript );
+                       }
                }
 
                return this;
 
                function root( elem, cur ) {
-                       return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ?
+                       return jQuery.nodeName(elem, "table") ?
                                (elem.getElementsByTagName("tbody")[0] ||
                                elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
                                elem;
@@ -162,6 +274,35 @@ jQuery.fn.extend({
        }
 });
 
+function buildFragment(args, nodes, scripts){
+       var fragment, cacheable, cached, cacheresults, doc;
+
+       if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && args[0].indexOf("<option") < 0 ) {
+               cacheable = true;
+               cacheresults = jQuery.fragments[ args[0] ];
+               if ( cacheresults ) {
+                       if ( cacheresults !== 1 ) {
+                               fragment = cacheresults;
+                       }
+                       cached = true;
+               }
+       }
+
+       if ( !fragment ) {
+               doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
+               fragment = doc.createDocumentFragment();
+               jQuery.clean( args, doc, fragment, scripts );
+       }
+
+       if ( cacheable ) {
+               jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
+       }
+
+       return { fragment: fragment, cacheable: cacheable };
+}
+
+jQuery.fragments = {};
+
 jQuery.each({
        appendTo: "append",
        prependTo: "prepend",
@@ -177,21 +318,21 @@ jQuery.each({
                        jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
                        ret = ret.concat( elems );
                }
-
-               return this.pushStack( ret, name, selector );
+               return this.pushStack( ret, name, insert.selector );
        };
 });
 
 jQuery.each({
-       remove: function( selector ) {
+       // keepData is for internal use only--do not document
+       remove: function( selector, keepData ) {
                if ( !selector || jQuery.multiFilter( selector, [ this ] ).length ) {
-                       if ( this.nodeType === 1 ) {
+                       if ( !keepData && this.nodeType === 1 ) {
                                cleanData( this.getElementsByTagName("*") );
-                               cleanData( [this] );
+                               cleanData( [ this ] );
                        }
 
                        if ( this.parentNode ) {
-                               this.parentNode.removeChild( this );
+                                this.parentNode.removeChild( this );
                        }
                }
        },
@@ -214,121 +355,92 @@ jQuery.each({
 });
 
 jQuery.extend({
-       clean: function( elems, context, fragment ) {
+       clean: function( elems, context, fragment, scripts ) {
                context = context || document;
 
                // !context.createElement fails in IE with an error but returns typeof 'object'
-               if ( typeof context.createElement === "undefined" )
+               if ( typeof context.createElement === "undefined" ) {
                        context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
-
-               // If a single string is passed in and it's a single tag
-               // just do a createElement and skip the rest
-               if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) {
-                       var match = /^<(\w+)\s*\/?>$/.exec(elems[0]);
-                       if ( match )
-                               return [ context.createElement( match[1] ) ];
                }
 
-               var ret = [], scripts = [], div = context.createElement("div");
+               var ret = [], div = context.createElement("div");
 
                jQuery.each(elems, function(i, elem){
-                       if ( typeof elem === "number" )
+                       if ( typeof elem === "number" ) {
                                elem += '';
+                       }
 
-                       if ( !elem )
-                               return;
+                       if ( !elem ) { return; }
 
                        // Convert html string into DOM nodes
-                       if ( typeof elem === "string" ) {
+                       if ( typeof elem === "string" && !rhtml.test( elem ) ) {
+                               elem = context.createTextNode( elem );
+
+                       } else if ( typeof elem === "string" ) {
                                // Fix "XHTML"-style tags in all browsers
-                               elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
-                                       return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
-                                               all :
-                                               front + "></" + tag + ">";
-                               });
+                               elem = elem.replace(rxhtmlTag, fcloseTag);
 
                                // Trim whitespace, otherwise indexOf won't work as expected
-                               var tags = elem.replace(/^\s+/, "").substring(0, 10).toLowerCase();
-
-                               var wrap =
-                                       // option or optgroup
-                                       !tags.indexOf("<opt") &&
-                                       [ 1, "<select multiple='multiple'>", "</select>" ] ||
-
-                                       !tags.indexOf("<leg") &&
-                                       [ 1, "<fieldset>", "</fieldset>" ] ||
-
-                                       tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
-                                       [ 1, "<table>", "</table>" ] ||
-
-                                       !tags.indexOf("<tr") &&
-                                       [ 2, "<table><tbody>", "</tbody></table>" ] ||
-
-                                       // <thead> matched above
-                                       (!tags.indexOf("<td") || !tags.indexOf("<th")) &&
-                                       [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||
-
-                                       !tags.indexOf("<col") &&
-                                       [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||
-
-                                       // IE can't serialize <link> and <script> tags normally
-                                       !jQuery.support.htmlSerialize &&
-                                       [ 1, "div<div>", "</div>" ] ||
-
-                                       [ 0, "", "" ];
+                               var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
+                                       wrap = wrapMap[ tag ] || wrapMap._default,
+                                       depth = wrap[0];
 
                                // Go to html and back, then peel off extra wrappers
                                div.innerHTML = wrap[1] + elem + wrap[2];
 
                                // Move to the right depth
-                               while ( wrap[0]-- )
+                               while ( depth-- ) {
                                        div = div.lastChild;
+                               }
 
                                // Remove IE's autoinserted <tbody> from table fragments
                                if ( !jQuery.support.tbody ) {
 
                                        // String was a <table>, *may* have spurious <tbody>
-                                       var hasBody = /<tbody/i.test(elem),
-                                               tbody = !tags.indexOf("<table") && !hasBody ?
+                                       var hasBody = rtbody.test(elem),
+                                               tbody = tag === "table" && !hasBody ?
                                                        div.firstChild && div.firstChild.childNodes :
 
-                                               // String was a bare <thead> or <tfoot>
-                                               wrap[1] == "<table>" && !hasBody ?
-                                                       div.childNodes :
-                                                       [];
+                                                       // String was a bare <thead> or <tfoot>
+                                                       wrap[1] == "<table>" && !hasBody ?
+                                                               div.childNodes :
+                                                               [];
 
-                                       for ( var j = tbody.length - 1; j >= 0 ; --j )
-                                               if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length )
+                                       for ( var j = tbody.length - 1; j >= 0 ; --j ) {
+                                               if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
                                                        tbody[ j ].parentNode.removeChild( tbody[ j ] );
-
+                                               }
                                        }
 
+                               }
+
                                // IE completely kills leading whitespace when innerHTML is used
-                               if ( !jQuery.support.leadingWhitespace && /^\s/.test( elem ) )
-                                       div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
+                               if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
+                                       div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
+                               }
 
                                elem = jQuery.makeArray( div.childNodes );
                        }
 
-                       if ( elem.nodeType )
+                       if ( elem.nodeType ) {
                                ret.push( elem );
-                       else
+                       } else {
                                ret = jQuery.merge( ret, elem );
+                       }
 
                });
 
                if ( fragment ) {
                        for ( var i = 0; ret[i]; i++ ) {
-                               if ( jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
+                               if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
                                        scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
                                } else {
-                                       if ( ret[i].nodeType === 1 )
+                                       if ( ret[i].nodeType === 1 ) {
                                                ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
+                                       }
                                        fragment.appendChild( ret[i] );
                                }
                        }
-
-                       return scripts;
                }
 
                return ret;
@@ -336,9 +448,8 @@ jQuery.extend({
 });
 
 function cleanData( elems ) {
-       for ( var i = 0, l = elems.length; i < l; i++ ) {
-               var id = elems[i][expando];
-               if ( id ) {
+       for ( var i = 0, elem, id; (elem = elems[i]) != null; i++ ) {
+               if ( (id = elem[expando]) ) {
                        delete jQuery.cache[ id ];
                }
        }