0

Possible Duplicate:
Get selected element's outer HTML

I have this code :

<html>
    <head></head>
    <body></body>
</html>

and with $('html').html() I only get :

    <head></head>
    <body></body>

how can I get the whole code? I mean, with also the parent of the element where I use .html()...

Community
  • 1
  • 1
markzzz
  • 45,272
  • 113
  • 282
  • 475
  • On the one hand this seems like an interesting question from the technical angle, but on the other hand: why would you want to do this with ``? For 95% of pages I've seen you could just say `"" + $("html").html() + ""`. – nnnnnn Oct 26 '11 at 09:36

5 Answers5

2

Try this jQuery extension:

jQuery.fn.outerHTML = function(s) {
    return (s) ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html();
}

You can call it like this:

$("html").outerHTML();

Credits go to this page.

Bas Slagter
  • 9,721
  • 7
  • 48
  • 74
1

Bit of a hack:

$('<div />').html($('html').clone()).html();

Might be slow in older browsers with a lot of HTML on the page, because it has to clone the whole thing.

Edit: If you want a jQuery function which does it, just write one:

$.fn.outerHtml = function (a) {
    if (a) {
        a = $(a).insertBefore(this);
        this.remove();
        return a;
    }
    return $('<div />').html($('html').clone()).html();
};

Then just call $('html').outerHtml().

Nathan MacInnes
  • 10,885
  • 4
  • 34
  • 48
0

I think there are many ways, eq. jQuery("html")[0].outerHTML; or jQuery("html").attr("outerHTML");

Edit: This isn't cross-browser, I forgot that. Firefox doesn't support this. There are (cloning) hacks for that.

Edit: See How do I do OuterHTML in firefox? for FF support.

Community
  • 1
  • 1
Samuli Hakoniemi
  • 17,864
  • 1
  • 57
  • 74
0

What about this:

$('<div>').append($('html').clone()).remove().html();
xdazz
  • 154,648
  • 35
  • 237
  • 264
0

Anyway, if you're trying to get <html> and it supposed to be the only <html> tag in a correct document - why not adding it manually to it's innerHTML?

Michael Sazonov
  • 1,531
  • 9
  • 20