Get the whole document's html with JavaScript/JQuery

前端 未结 8 1282
无人及你
无人及你 2021-02-14 16:54

I know it\'s already discussed here, but there were no solution to get the whole document (including doctype).

$(document).html(); returns null

8条回答
  •  没有蜡笔的小新
    2021-02-14 17:10

    This is a function which has support in IE6+, it does't use outerHTML for even more support, it adds the doctype and uses a few tricks to get the html tag and its attributes. In order to receive a string with the doctype, and doesn't use outerHTML so it supports every browser. It uses a few tricks to get the html tag. Add this code:

    document.fullHTML = function () {
        var r = document.documentElement.innerHTML, t = document.documentElement.attributes, i = 0, l = '',
            d = '';
        for (; i < t.length; i += 1) l += ' ' + t[i].name + '="' + t[i].value + '"';
        return d+'\n' + r + '';
    }
    

    Now, you can run this function:

    console.log(document.fullHTML());
    

    This will return the HTML and doctype.

    I ran this on example.com, here are the results

提交回复
热议问题