Get entire html document using JavaScript / jQuery

I know this has already been discussed here, but there was no solution to get the whole document (including doctype).

$(document).html(); returns null ...

+6
source share
7 answers

This will give you all the HTML:

 document.documentElement.outerHTML 

Unfortunately, it does not return doctype. But you can use document.doctype to get it and glue the two together.

+11
source

try it.

 $("html").html() 

document is a variable that it is not an html tag.

EDIT

To get doctype, you can use

 document.doctype 
+4
source

This is a feature that has support in IE6 +, it does not use outerHTML for more support, adds doctype, and uses a few tricks to get the html tag and its attributes. To get a line with doctype and not using outerHTML , so it supports every browser. It uses a few tricks to get the html tag. Add this code:

 document.fullHTML = function () { var r = document.documentElement.innerHTML, t = document.documentElement.attributes, i = 0, l = '', d = '<!DOCTYPE ' + document.doctype.name + (document.doctype.publicId ? ' PUBLIC "' + document.doctype.publicId + '"' : '') + (!document.doctype.publicId && document.doctype.systemId ? ' SYSTEM' : '') + (document.doctype.systemId ? ' "' + document.doctype.systemId + '"' : '') + '>'; for (; i < t.length; i += 1) l += ' ' + t[i].name + '="' + t[i].value + '"'; return d+'\n<html' + l + '>' + r + '</html>'; } 

Now you can run this function:

 console.log(document.fullHTML()); 

This will return HTML and doctype.

I ran this on example.com , here are the results

+2
source

You can do

 new XMLSerializer().serializeToString(document); 

for all browsers newer than IE 9

+2
source
 document.documentElement.innerHTML 

will return you all the markup of the document as a string

to get the whole doctype read this

+1
source

I'm not sure about getting the full doc.but, what you can do, you can get the contents of the html seprately and doctype tag separately.

$('html').html() for content and document.doctype to get doctype

+1
source

I don't think there is direct access to the whole document (including doctype), but this works:

 $.get(document.location, function(html) { // use html (which is the complete source code, including the doctype) }); 
0
source

All Articles