I used $(document).html(), but that threw an error...  is there a way to get everything?
            Asked
            
        
        
            Active
            
        
            Viewed 9.5k times
        
    58
            
            
         
    
    
        Naveed
        
- 41,517
- 32
- 98
- 131
 
    
    
        Justin Lee
        
- 909
- 4
- 9
- 19
5 Answers
71
            
            
        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   
 
    
    
        Patrick McElhaney
        
- 57,901
- 40
- 134
- 167
71
            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>";
}
 
    
    
        Jimmie R. Houts
        
- 7,728
- 2
- 31
- 38
- 
                    how about getting the doctype? – Sebastian Patane Masuelli Aug 18 '12 at 17:59
- 
                    @Sebastian Not sure if you can, see [this answer](http://stackoverflow.com/questions/3043820/jquery-check-doctype) – Jimmie R. Houts Aug 19 '12 at 01:16
- 
                    This could work, but if you're replacing a page with a whole other page, you'll end up having multiple html tags. – Kirk Douglas Jr Feb 01 '18 at 17:12
4
            
            
        Use:
document.body.innerHTML
 
    
    
        Diodeus - James MacFarlane
        
- 112,730
- 33
- 157
- 176
- 
                    2If you want the entire document html you should use: `window.document.innerHTML` – simo Jul 16 '12 at 15:44
- 
                    2@simo: `document` doesn't have an `innerHTML` property in any browsers i still use. – cHao Jul 29 '13 at 22:27
3
            
            
        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
 
    
    
        FurloSK
        
- 441
- 2
- 14
2
            
            
        $("html").html() would get everything but the outer most html tags.
 
    
    
        Max Schmeling
        
- 12,363
- 14
- 66
- 109