Skip to content Skip to sidebar Skip to footer

Namespace Attributes Not Present In .outerhtml

In HTML5/JavaScript, if I create a namespaced dom node programmatically, like so: svgElt = document.createElementNS('http://www.w3.org/2000/svg', 'svg') the node 'knows' it's own

Solution 1:

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 = newXMLSerializer().serializeToString(svgElt);
console.log(serialized);

Solution 2:

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).

functionouterXHTML(node){
    var nsx = "http://www.w3.org/1999/xhtml";
    var xdoc = document.implementation.createDocument(nsx, 'html');
    xdoc.documentElement.appendChild(node);
    return node.outerHTML;
}
functioninnerXHTML(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

Post a Comment for "Namespace Attributes Not Present In .outerhtml"