This small function creates an XML representation (DOM compliant) of the current HTML document. It is only necessary for Internet Explorer, as on Mozilla and other browsers the HTML nodes are already XML nodes.
function document2DOM() { var root = new ActiveXObject("MSXML.DOMDocument"); root.async = false; root.resolveExternals = false; loadNode(root,root,document); return root; } function loadNode(root,parentNode,htmlNode) { switch (htmlNode.nodeType) { // Comment node case 8 : parentNode.appendChild( root.createComment( htmlNode.nodeValue ) ); return; // CDATA section case 4: parentNode.appendChild( root.createCDATASection( htmlNode.nodeValue ) ); return; // Text node case 3 : parentNode.appendChild( root.createTextNode( htmlNode.nodeValue) ); return; // Document Node case 9 : var children = htmlNode.childNodes; for (var i = 0; i < children.length; i++) { loadNode(root,root,children[i]); } return; // Element node case 1 : var element = root.createElement( htmlNode.nodeName ) parentNode.appendChild(element); // Set all attributes for (var i = 0; i < htmlNode.attributes.length; i++) { var attr = htmlNode.attributes[i]; if (attr.nodeValue && attr.specified) { var attrNode = root.createAttribute(attr.nodeName); attrNode.value = attr.nodeValue; element.setAttributeNode(attrNode); } } // Now process the children var children = htmlNode.childNodes; for (var i = 0; i < children.length; i++) { loadNode(root,element,children[i]); } return; } } function test() { var result = document2DOM(); alert(result.xml) }
Press to test this function. (Internet Explorer only)
|
doc2dom.js ( 1 Kb ) |