How to get the entire document HTML as a string?

前端 未结 15 1961
暖寄归人
暖寄归人 2020-11-22 17:00

Is there a way in JS to get the entire HTML within the html tags, as a string?

document.documentElement.??
15条回答
  •  旧巷少年郎
    2020-11-22 17:49

    I am using outerHTML for elements (the main container), and XMLSerializer for anything else including , random comments outside the container, or whatever else might be there. It seems that whitespace isn't preserved outside the element, so I'm adding newlines by default with sep="\n".

    function get_document_html(sep="\n") {
        let html = "";
        let xml = new XMLSerializer();
        for (let n of document.childNodes) {
            if (n.nodeType == Node.ELEMENT_NODE)
                html += n.outerHTML + sep;
            else
                html += xml.serializeToString(n) + sep;
        }
        return html;
    }
    
    console.log(get_document_html().slice(0, 200));

提交回复
热议问题