views:

79

answers:

4

I am trying to retrieve the full HTML of a page, so far I am using:

$('*').html()

Is there a better way (also this excludes the <html> tags at the top)?

+3  A: 

I tried $('html').html() but this of course excludes the html element.

$('html').parent().html() didn't work either because the root has no parents.

$(document).html() also fails

You could get the contents and then capture any attributes from the html element that you require, at leas then you can rebuild it if needed

Edit based on comment: Just found this cross browser OuterHTML plugin http://yelotofu.com/2008/08/jquery-outerhtml/

Neil Aitken
+1 I tried various approaches, including outerHTML but that isnt a standard.
James Westgate
A: 
function GetPageHtml()
{
   return $('html')[0] + $('html').html() + '</html>';
}
Andreas Bonini
but what about potential attributes of the HTML tag?
T. Stone
@T. Stone: nice catch. Fixed :)
Andreas Bonini
+2  A: 

Not sure what you're using this for, but would using $.get to fetch the location.href be a reasonable workaround (as a bonus you'd get the DOCTYPE and other header-ish stuff as well).

$.get(location.href, function(html) {
    alert(html);
});

Ok maybe that's kinda silly...

T. Stone
It's a little crazy, but it would certainly work :)
Neil Aitken
A: 

This does the trick:

html = $('<dummy>').append($('html').clone()).remove().html();

farzan