Firefox outerhtml Implementation Code _JAVASCRIPT skills

Source: Internet
Author: User
Tags tagname

Reducing the number of DOM speeds the browser's construction of DOM tree and render tree during parsing pages, improving page performance. To this end, we can the page in the first screen rendering the invisible part of the HTML temporary textarea, and so on to complete the rendering after processing this part of HTML to achieve this goal. To add the temporary HTML content in the textarea to the page, it is easiest to use the element's outerHTML attribute, but there is no outerhtml defined in the DOM standard, and the supported browsers are Ie6+,safari, Operal, and Chrome. It is not supported by the tested ff4.0-. So we're going to implement a outerhtml that can be used across browsers.
outerHTML is to get or set HTML that contains the element label itself. Here is the implementation code:

Copy Code code as follows:

if (typeof htmlelement!== "undefined" &&! (" outerHTML "in Htmlelement.prototype)") {
Console.log ("defined outerhtml");
htmlelement.prototype.__definesetter__ ("outerHTML", function (str) {
var fragment = Document.createdocumentfragment ();
var div = document.createelement ("div");
div.innerhtml = str;
For (var i=0, n = div.childNodes.length; i<n; i++) {
Fragment.appendchild (Div.childnodes[i]);
}
This.parentNode.replaceChild (fragment, this);
});
//
htmlelement.prototype.__definegetter__ ("outerHTML", function () {
var tag = This.tagname;
var attributes = This.attributes;
var attr = [];
for (var name in attributes) {//Traverse prototype chain member
for (var i=0,n = attributes.length i<n; i++) {//n specified number of properties
if (attributes[i].specified) {
Attr.push (attributes[i].name + ' = "' + Attributes[i].value + '");
}
}
Return (!!! this.innerhtml)?
' < ' + tag + ' + attr.join (') + ' > ' +this.innerhtml+ ' </' +tag+ ' > ':
' < ' + tag + ' +attr.join (') + '/> ');
});
}

Code Description:
The 1 Code first conditions to monitor whether the browser supports outerhtml to avoid overwriting the browser native implementation.
2 "__definesetter__", "__definegetter__" is a private aspect of the Firefox browser. Define the actions to be performed when setting the property value and getting the property, respectively.
3 frequent reflow affect performance in "__definesetter__" "outerhtml" to avoid too many elements in the Insert page. The document fragment object fragment is used to hold the DOM element that needs to be inserted into the page.
4 Use the Element attributes property in "__definegetter__" "outerhtml" to traverse the property specified for the element. Combining innerHTML Returns an HTML string containing the original itself.
Test code:
Copy Code code as follows:

<! DOCTYPE html>
<meta charset= "Utf-8"/>
<title>outerHTML</title>
<body>
<div id= "Content" class= "Test" >
<p>this are <strong>paragraph</strong> with a list following it</p>
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
</ul>
</div>
<script>
if (typeof htmlelement!== "undefined" &&! (" outerHTML "in Htmlelement.prototype)") {
Console.log ("defined outerhtml");
htmlelement.prototype.__definesetter__ ("outerHTML", function (str) {
var fragment = Document.createdocumentfragment ();
var div = document.createelement ("div");
div.innerhtml = str;
For (var i=0, n = div.childNodes.length; i<n; i++) {
Fragment.appendchild (Div.childnodes[i]);
}
This.parentNode.replaceChild (fragment, this);
});
//
htmlelement.prototype.__definegetter__ ("outerHTML", function () {
var tag = This.tagname;
var attributes = This.attributes;
var attr = [];
for (var name in attributes) {//Traverse prototype chain member
for (var i=0,n = attributes.length i<n; i++) {//n specified number of properties
if (attributes[i].specified) {
Attr.push (attributes[i].name + ' = "' + Attributes[i].value + '");
}
}
Return (!!! this.innerhtml)?
' < ' + tag + ' + attr.join (') + ' > ' +this.innerhtml+ ' </' +tag+ ' > ':
' < ' + tag + ' +attr.join (') + '/> ');
});
}
var content = document.getElementById ("content");
Alert (content.outerhtml)
</script>
</body>

Suppose you want to get the outerhtml of P of <p id= "Outerid" >sdfdsdfsd</p>
Code:
Copy Code code as follows:

var _p = document.getElementById (' Outerid ');
_p = _p.clonenode ();
var _div = document.createelement ();
_div.appendchild (_p);
alert (_div.innerhtml); is the outerhtml of P;

Firefox does not have outerhtml use the following methods to solve
Copy Code code as follows:

/**
* Compatible with Firefox outerhtml use the following code, Firefox can use the element.outerhtml
**/
if (window. HtmlElement) {
htmlelement.prototype.__definesetter__ ("outerHTML", function (SHTML) {
var r=this.ownerdocument.createrange ();
R.setstartbefore (this);
var df=r.createcontextualfragment (SHTML);
This.parentNode.replaceChild (Df,this);
return SHTML;
});
htmlelement.prototype.__definegetter__ ("outerHTML", function () {
var attr;
var attrs=this.attributes;
var str= "<" +this.tagname.tolowercase ();
for (Var i=0;i<attrs.length;i++) {
Attr=attrs[i];
if (attr.specified)
str+= "" +attr.name+ ' = "' +attr.value+ '";
}
if (!this.canhavechildren)
return str+ ">";
return str+ ">" +this.innerhtml+ "</" +this.tagname.tolowercase () + ">";
});
htmlelement.prototype.__definegetter__ ("Canhavechildren", function () {
Switch (This.tagName.toLowerCase ()) {
Case "Area":
Case "Base":
Case "Basefont":
Case "Col":
Case "Frame":
Case "HR":
Case "IMG":
Case "BR":
Case "Input":
Case "Isindex":
Case "link":
Case "META":
Case "param":
return false;
}
return true;
});
}

The test is valid.
A new solution to insertadjacenthtml compatibility
Copy Code code as follows:

---Insert HTML code at the end of the component
function inserthtm (Op,code,isstart) {
if (DVBBS_ISIE5)
Op.insertadjacenthtml (Isstart?) "Afterbegin": "Afterend", code);
else{
var range=op.ownerdocument.createrange ();
Range.setstartbefore (OP);
var fragment = range.createcontextualfragment (code);
if (Isstart)
Op.insertbefore (Fragment,op.firstchild);
Else
Op.appendchild (fragment);
}
}

A reference to inner/outerhtml in NC6
DOM Level 1 has no methods to allow for insertion of unparsed HTML into the document tree (as IE allows with Insertadjacen Thtml or assignment to inner/outerhtml). NN6 (currently in beta as NN6PR3) know supports of innerhtmlproperty, so, you can read or write the I Nnerhtml of a page element like in ie4+. NN6 also provides a DOM Level 2 compliant Range object to which a createcontextualfragment (' HTML source string ') is added To spare Dom scripters the task of parsing HTML and creating DOM elements. Create a range with var range = Document.createrange (); Then you should set it start point to the element where you want to insert the HTML for instance var someelement = Docume Nt.getelementbyid (' ElementID '); Range.setstartafter (someelement); Then Create a document fragment from the HTML source to insert for example var Docfrag = Range.createcontextualfragmen T (' <p>kibology for all.</p> '), and insert it with DOM methods Someelement.appendchild (Docfrag); The NeTscape JavaScript 1.5 version even provides so called Setters for properties which together with the ability to prototype The DOM elements allows to emulate setting of OUTERHMTL for Nn6:<script language= "JavaScript1.5" >if (Navigator.appna me = = ' Netscape ') {HTMLElement.prototype.outerHTML setter = function (html) {this.outerhtmlinput = html; var range = thi S.ownerdocument.createrange (); Range.setstartbefore (this); var Docfrag = range.createcontextualfragment (HTML); This.parentNode.replaceChild (Docfrag, this); }}</script> If You insert this SCRIPT block your can then write cross browser code assigning to. InnerHTML. outerhtml For instance Document.body.innerHTML = "<p>scriptology for all</p>"; which works with both IE4/5 and NN6. The following provides getter functions for. Outerhtmlto allow to read those properties in NN6 in a IE4/5 compatible. The "while" scheme of traversing the document tree should to the right direction the code example MIGht not satisfy your needs as there are subtle if difficulties to trying the HTML source from the document reproduce E. For yourself whether and improve it as needed to cover other exceptions than those The empty elements and the textarea element). HTMLElement.prototype.innerHTML setter = function (str) {var r = This.ownerDocument.createRange (); r.selectnodecontents (this); R.deletecontents (); var df = r.createcontextualfragment (str); This.appendchild (DF); return str;} HTMLElement.prototype.outerHTML setter = function (str) {var r = This.ownerDocument.createRange (); R.setstartbefore ( this); var df = r.createcontextualfragment (str); This.parentNode.replaceChild (DF, this); return str;}
HTMLElement.prototype.innerHTML getter = function () {return getinnerhtml (this);}
function getinnerhtml (node) {var str = ""; for (var i=0; i<node.childnodes.length; i++) str = getouterhtml (Node.childNodes.item (i)); return str;}
HTMLElement.prototype.outerHTML getter = function () {return getouterhtml (this)}
function getouterhtml (node) {var str = ""; Switch (node.nodetype) {Case 1://element_node str + + ' < ' + node.nodename; for (var i=0; i<node.attributes.length; i++) {if (Node.attributes.item (i). NodeValue!= null) {str = "" str = Node.attributes.item (i). nodename; STR + + "=\"; str = Node.attributes.item (i). NodeValue; str + = "" "; } }
if (Node.childNodes.length = = 0 && leafelems[node.nodename]) str + = ">"; else {str = ">"; str + + getinnerhtml (node); STR + + "<" + Node.nodename + ">"} break; Case 3://text_node str = node.nodevalue; Break Case 4://Cdata_section_node str = "<! [cdata["+ Node.nodevalue +"]]> "; Break Case 5://Entity_reference_node str = "&" + Node.nodename + ";" break;
Case 8://Comment_node str = "<!--" + Node.nodevalue + "-->" break; }
return str;}
var _leafelems = ["IMG", "HR", "BR", "INPUT"];var leafelems = {};for (var i=0; i<_leafelems.length; i++) Leafelems[_lea Felems[i]] = true;
Then we can block it into a JS reference
if (/mozilla\/5\.0/.test (navigator.useragent)) document.write (' <script type= "Text/javascript" src= " Mozinnerhtml.js "></sc ' + ' ript> ');
Copy Code code as follows:

<script language= "JavaScript" type= "Text/javascript" >
<!--
var emptyelements = {hr:true, br:true, Img:true, input:true}; var specialelements = {Textarea:true};
HTMLElement.prototype.outerHTML getter = function () {
Return getouterhtml (this);
}
function getouterhtml (node) {
var html = ';
Switch (node.nodetype) {
Case Node.ELEMENT_NODE:html + = ' < '; HTML + node.nodename; if (!specialelements[node.nodename]) {
for (var a = 0; a < node.attributes.length; a++)
HTML + + node.attributes[a].nodename.touppercase () + ' = ' + Node.attributes[a].nodevalue + ' ";
html + = ' > ';
if (!emptyelements[node.nodename]) {
HTML + node.innerhtml;
html + + ' <\/' + node.nodename + ' > ';
}
} else
Switch (node.nodename) {
Case ' TEXTAREA ': for (var a = 0; a < node.attributes.length; a++)
if (node.attributes[a].nodename.tolowercase ()!= ' value ')
Html
+ = ' + node.attributes[a].nodename.touppercase () + ' = ' + node.attributes[a].nodevalue
+ '"';
Else
var content = Node.attributes[a].nodevalue;
html + = ' > '; HTML + content; html + + ' <\/' + node.nodename + ' > '; Break
} break;
Case Node.TEXT_NODE:html + = Node.nodevalue; Break
Case Node.COMMENT_NODE:html + = ' <! ' + '--' + Node.nodevalue + '--' + ' > '; Break
}
return HTML;
}
-->
</script>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.