How to get the entire document HTML as a string?

How to get the entire document HTML as a string?

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

Solutions/Answers:

Solution 1:

MS added the outerHTML and innerHTML properties some time ago.

According to MDN, outerHTML is supported in Firefox 11, Chrome 0.2, Internet Explorer 4.0, Opera 7, Safari 1.3, Android, Firefox Mobile 11, IE Mobile, Opera Mobile, and Safari Mobile. outerHTML is in the DOM Parsing and Serialization specification.

See quirksmode for browser compatibility for what will work for you. All support innerHTML.

var markup = document.documentElement.innerHTML;
alert(markup);

Solution 2:

You can do

new XMLSerializer().serializeToString(document)

in browsers newer than IE 9

See https://caniuse.com/#feat=xml-serializer

Solution 3:

I believe document.documentElement.outerHTML should return that for you.

According to MDN, outerHTML is supported in Firefox 11, Chrome 0.2, Internet Explorer 4.0, Opera 7, Safari 1.3, Android, Firefox Mobile 11, IE Mobile, Opera Mobile, and Safari Mobile. outerHTML is in the DOM Parsing and Serialization specification.

Related:  Find all text nodes in HTML page [duplicate]

The MSDN page on the outerHTML property notes that it is supported in IE 5+. Colin’s answer links to the W3C quirksmode page, which offers a good comparison of cross-browser compatibility (for other DOM features too).

Solution 4:

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

The suggestion document.documentElement.innerHTML; returned <head> ... </body>

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

The suggestion document.documentElement.outerHTML; returned <html><head> ... </body></html>
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('<!DOCTYPE HTML>' + '\n' + document.documentElement.outerHTML);

Solution 5:

You can also do:

document.getElementsByTagName('html')[0].innerHTML

You will not get the Doctype or html tag, but everything else…

Related:  Setting the width of a dropdown list in Bootstrap 3.0

Solution 6:

document.documentElement.outerHTML