document
is not an element, so it doesn't have a way to render itself as HTML. There's currently no compatible way to get the entire actual source, short of an Ajax request for the current URL -- and even that may not return the same thing.
$('html').html()
will get you everything inside the <html>
tag. In most cases, that's plenty. Tack on a <!DOCTYPE html>
, and you have yourself a valid HTML document (assuming the original source represented one).
document.documentElement.outerHtml
to get most of the document. That'll include the <html>
tag, but not anything validly outside of it. Specifically, it won't get you the doctype, or any comments that appear before or after.
For modern browsers, a new XMLSerializer
may get you the current contents of the document. It doesn't work in IE8, though.
And of course, all of these methods of telling the browser to HTMLify the document, return the contents as the browser understands them. The browser may mangle invalid HTML to get it to fit within the document. For example, stuff appearing after the <body>
element may be moved to inside it.