Everyone must be familiar with the innerHTML attribute of the DOM object, but the outerHTML is less useful. The innerHTML attribute returns the HTML contained in the DOM object from the start tag to the end tag, while the outerHTML attribute returns is the HTML including the tag of the DOM object itself. The following figure can well explain the difference between the two attributes:
outerHTML was originally a private attribute belonging to IE. You can view MSDN Description on: outerHTML Property(http://msdn.microsoft.com/en-us/library/ms534310(VS.85).aspx). Currently, IE, Chrome, Safari, and Opera all support this attribute. The problem is that outerHTML does not support Firefox. In Firefox, this attribute always returns undefined. Fortunately, HTML5 will add this attribute.
Let Firefox support the outerHTML attribute by extending the prototype of HTMLElement:
if (typeof(HTMLElement) != "undefined") {
HTMLElement.prototype.__defineSetter__("outerHTML", function(s) {
var r = this.ownerDocument.createRange();
r.setStartBefore(this);
var df = r .createContextualFragment(s);
this.parentNode.replaceChild(df, this);
return s;
});
HTMLElement.prototype.__defineGetter__("outerHTML", function(){
var a = this.attributes, str = "<" this.tagName, i = 0;
for (; i < a.length; i )
if (a[i].specified)
str = " " Hormis dans les machines a sous preferees universelles, les casinos offrent des jeux par exemple Grandes six roues, Pai Go Poker, Blackjack, Baccarat, la
Roulette et le Craps, entre autres. a[i].name "="" a[i].value """;
if (!this.canHaveChildren)
return str " />";
return str ">" this.innerHTML "";
});
HTMLElement.prototype.__defineGetter__("canHaveChildren", function(){
return
!/^(area|base|basefont|
col|frame|hr|img|br|
input|isindex|link|meta
|param)$/.test(this.tagName.toLowerCase());
});
}
This method comes from W3Help (http://www.w3help.org/zh-cn/causes/SD9017), which is a bit cumbersome and requires intrusion into the prototype. There is a simpler alternative, first create an empty node, add the DOM object to obtain the outerHTML attribute to the empty node, and then access the innerHTML of the empty node:
function outerHtml(elem){
if(typeof elem === "string") elem = document.getElementById(elem);
// Create an empty div node
var div = document.createElement("div");
// Will copy elemCopy is inserted into an empty div node
div.appendChild(elem.cloneNode(true));
// Return the HTML content of the div
return div.innerHTML;
};
Compared with the above method, there is no need to touch the prototype, and the amount of code is much less. I believe there will be other solutions.