To get HTML content of an element using jQuery, use the html() method. The html() method gets the html contents of the first matched element.
The * selector selects all elements in the document, including html, head and body. If the * selector is used together with another element, it selects all child elements within the specified element. Tip: The * selector can be heavy to process for some browsers.
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
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>";
}
Use:
document.body.innerHTML
$("html").html()
would get everything but the outer most html tags.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With