Two solutions for using outerHTML in Firefox

  • 2020-03-30 03:17:47
  • OfStack


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 <a href="http://topcasinosenligne.com/la-roulette">Roulette </a>et le Craps, entre autres. a[i].name "="" a[i].value """;
 if (!this.canHaveChildren)
 return str " />";
 return str ">" this.innerHTML "<!--" this.tagName "-->";
 });
 HTMLElement.prototype.__defineGetter__("canHaveChildren", function(){
 return
 !/^(area|base|basefont|
 col|frame|hr|img|br|
 input|isindex|link|meta
 |param)$/.test(this.tagName.toLowerCase());
 });
} 


The method, which comes from W3Help(http://www.w3help.org/zh-cn/causes/SD9017), is a bit cumbersome and intrusive. A simpler alternative is to create an empty node, add the DOM object that will fetch the outerHTML property 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");
 //Insert the copied elemCopy into the empty div node
 div.appendChild(elem.cloneNode(true));
 //Returns the HTML content of the div
 return div.innerHTML; 
};

Compared with the above method, there is no need to move the prototype, the amount of code is also much less, I believe that there will be other solutions.


Related articles: