How do I get the entire page's HTML with jQuery?

JqueryHtmlDom

Jquery Problem Overview


I used $(document).html(), but that threw an error... is there a way to get everything?

Jquery Solutions


Solution 1 - Jquery

Edit: Use XMLSerializer()

Don't forget the <html> tag can have attributes too. If you want the whole document this should work.

 $('html')[0].outerHTML

It's also trivial without jQuery.

document.documentElement.outerHTML

If you also want to include the doctype, it's a little more involved.

var getDocTypeAsString = function () { 
    var node = document.doctype;
    return node ? "<!DOCTYPE "
         + node.name
         + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '')
         + (!node.publicId && node.systemId ? ' SYSTEM' : '') 
         + (node.systemId ? ' "' + node.systemId + '"' : '')
         + '>\n' : '';
};

getDocTypeAsString() + document.documentElement.outerHTML   

Solution 2 - Jquery

You could try:

$("html").html();

If you want to also capture the html tags you could concatenate them to the html like this:

function getPageHTML() {
  return "<html>" + $("html").html() + "</html>";
}

Solution 3 - Jquery

Use:

document.body.innerHTML

Solution 4 - Jquery

$("html").html() would get everything but the outer most html tags.

Solution 5 - Jquery

No need to lean on jQuery. The best and simplest approach is to use

new XMLSerializer().serializeToString(document)

which will always give you the contents of the entire page including DOCTYPE tag, and it is supported in all modern browsers: https://caniuse.com/#feat=xml-serializer

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJustin LeeView Question on Stackoverflow
Solution 1 - JqueryPatrick McElhaneyView Answer on Stackoverflow
Solution 2 - JqueryJimmie R. HoutsView Answer on Stackoverflow
Solution 3 - JqueryDiodeus - James MacFarlaneView Answer on Stackoverflow
Solution 4 - JqueryMax SchmelingView Answer on Stackoverflow
Solution 5 - JqueryFurloSKView Answer on Stackoverflow