dtrunk
dtrunk

Reputation: 4805

Get the whole document's html with JavaScript/JQuery

I know it's already discussed here, but there were no solution to get the whole document (including doctype).

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

Upvotes: 8

Views: 16576

Answers (8)

user187676
user187676

Reputation:

You can do

new XMLSerializer().serializeToString(document);

for all browsers newer than IE 9

Upvotes: 9

Ashok Raj
Ashok Raj

Reputation: 11

I have done it on browser's console

document.documentElement;

Upvotes: 0

Downgoat
Downgoat

Reputation: 14361

This is a function which has support in IE6+, it does't use outerHTML for even more support, it adds the doctype and uses a few tricks to get the html tag and its attributes. In order to receive a string with the doctype, and doesn't use 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 the HTML and doctype.

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

Upvotes: 4

Milind Anantwar
Milind Anantwar

Reputation: 82241

I'm not sure about getting the complete doc.but what you can do is,you can get the content of html tag seprately and doctype seprately.

$('html').html() for content and document.doctype for getting the doctype

Upvotes: 1

Mortalus
Mortalus

Reputation: 10712

try this.

$("html").html()

document is a variable it dose not represent the html tag.

EDIT

To get the doctype one could use

document.doctype

Upvotes: 4

Ph0en1x
Ph0en1x

Reputation: 10067

document.documentElement.innerHTML 

will return you all document markup as string

to get the whole doctype read this

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

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

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

Upvotes: 0

Jan Hančič
Jan Hančič

Reputation: 53931

This will get you all the HTML:

document.documentElement.outerHTML

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

Upvotes: 14

Related Questions