2

This event is triggered when I make it:

$(document).on('dblclick', function() {
    alert($(document).html());
});

But the exception is thrown in the console:

Timestamp: 20.7.2013 18:59:35
Error: TypeError: t is null
Source File: http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js
Line: 5

Is this a jQuery related issue or I'm using a wrong approach to get entire HTML of a current HTML document?

3 Answers3

1

If you want everything, including the DOCTYPE and understand that it is generated source and not original source, you can use XMLSerializer on document.

$(document).on('dblclick', function() {
    alert(new XMLSerializer().serializeToString(document));
});
Paul S.
  • 64,864
  • 9
  • 122
  • 138
0

Try this code rather :

$(document).on('dblclick', function() {
    alert($('html').html());
});
Lucas Willems
  • 6,673
  • 4
  • 28
  • 45
-1

document is not an element, so it doesn't have a way to render itself as HTML. There's currently no compatible way to get the entire actual source, short of an Ajax request for the current URL -- and even that may not return the same thing.

$('html').html() will get you everything inside the <html> tag. In most cases, that's plenty. Tack on a <!DOCTYPE html>, and you have yourself a valid HTML document (assuming the original source represented one).

document.documentElement.outerHtml to get most of the document. That'll include the <html> tag, but not anything validly outside of it. Specifically, it won't get you the doctype, or any comments that appear before or after.

For modern browsers, a new XMLSerializer may get you the current contents of the document. It doesn't work in IE8, though.

And of course, all of these methods of telling the browser to HTMLify the document, return the contents as the browser understands them. The browser may mangle invalid HTML to get it to fit within the document. For example, stuff appearing after the <body> element may be moved to inside it.

cHao
  • 84,970
  • 20
  • 145
  • 172