How to get the entire document HTML as a string?

前端 未结 15 1992
暖寄归人
暖寄归人 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:55

    I tried the various answers to see what is returned. I'm using the latest version of Chrome.

    The suggestion document.documentElement.innerHTML; returned ...

    Gaby's suggestion document.getElementsByTagName('html')[0].innerHTML; returned the same.

    The suggestion document.documentElement.outerHTML; returned ... which is everything apart from the 'doctype'.

    You can retrieve the doctype object with document.doctype; This returns an object, not a string, so if you need to extract the details as strings for all doctypes up to and including HTML5 it is described here: Get DocType of an HTML as string with Javascript

    I only wanted HTML5, so the following was enough for me to create the whole document:

    alert('' + '\n' + document.documentElement.outerHTML);

提交回复
热议问题