Created
January 12, 2014 12:51
-
-
Save kawanet/8384221 to your computer and use it in GitHub Desktop.
This implements outerHTML method which jQuery is missing for long.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This implements outerHTML method which jQuery is missing for long. | |
* @returns {String} outerHTML | |
* @example | |
* $("<p>foo</p>").addClass("bar").html(); // => "foo" | |
* $("<p>foo</p>").addClass("bar").outerHTML(); // => "<p class="bar">foo</p>" | |
*/ | |
jQuery.prototype.outerHTML = function(){ | |
var wrap = new jQuery("<div/>"); | |
var elem = this.first(); | |
if (elem.parent().length) elem = elem.clone(); | |
return wrap.append(elem).html(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also: http://jsperf.com/outerhtml-vs-jquery-clone-hack/5
jQuery には outerHTML メソッドがない。html() メソッドは innerHTML になる。
clone().wrap().parent().html() 方式より上記の append(this.clone()).html() が少し速いらしい。
もっと速いプラグインの実装がいくつかあるみたいだけど、シンプルなので書いてみた。
cheerio でも動く互換コードが欲しかったんだけど、cheerio は自前の toString() メソッドがあるのに気づいて orz