In HTML5/JavaScript, if I create a namespaced dom node programmatically, like so:
svgElt = document.createElementNS(\"http://www.w3.org/2000/svg\", \'svg\')
You can simply use an XMLSerializer for this, which will stringify your DOM tree to xml and thus preserve the namespaces.
const svgElt = document.createElementNS("http://www.w3.org/2000/svg", 'svg')
const serialized = new XMLSerializer().serializeToString(svgElt);
console.log(serialized);
Please read the comments under question first.
Here is how we get html with namespace info by "xhtml-ifying" the dom node, and then calling .outerHTML
, which will then be xhtml (and have the namespace info the html is lacking).
function outerXHTML(node){
var nsx = "http://www.w3.org/1999/xhtml";
var xdoc = document.implementation.createDocument(nsx, 'html');
xdoc.documentElement.appendChild(node);
return node.outerHTML;
}
function innerXHTML(node){
var nsx = "http://www.w3.org/1999/xhtml";
var xdoc = document.implementation.createDocument(nsx, 'html');
xdoc.documentElement.appendChild(node);
return node.innerHTML;
}
(clone node first if it should remain in original document.)
related question (x/html conversion)
related question (document creation)
fiddle for testing the html to xhtml conversion
test Kaiido version with arbitrary HTML string from textbox