namespace attributes not present in .outerHTML

前端 未结 2 1902
清歌不尽
清歌不尽 2021-01-27 05:26

In HTML5/JavaScript, if I create a namespaced dom node programmatically, like so:

svgElt = document.createElementNS(\"http://www.w3.org/2000/svg\", \'svg\')


        
相关标签:
2条回答
  • 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);

    0 讨论(0)
  • 2021-01-27 05:40

    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

    0 讨论(0)
提交回复
热议问题