Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 475
dtrunk Avatar asked Jan 31 '13 08:01

dtrunk


People also ask

How do I get the whole HTML in jQuery?

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.

How do you select an entire document in jQuery?

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.

How will you get all the matching tags in a HTML file using JavaScript?

If you want to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc), use the querySelectorAll() method.


2 Answers

You can do

new XMLSerializer().serializeToString(document);

for all browsers newer than IE 9

like image 153
Era Avatar answered Oct 27 '22 19:10

Era


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

like image 38
Downgoat Avatar answered Oct 27 '22 19:10

Downgoat