39

Say I have this HTML:

<ul>
  <li id="example"><strong>Awesome</strong> example text</li>
</ul>

I want to be able to do something like $('#example').html() but right now doing that obviously only gets <strong>Awesome</strong> example text.

So how can I get the HTML including the selected element?

ie. <li id="example"><strong>Awesome</strong> example text</li>

I'm using jQuery 1.4.4.

Shpigford
  • 24,748
  • 58
  • 163
  • 252

5 Answers5

56

In this specific case:

var outerHTML = $("<div />").append($('#example').clone()).html();

See this page for more details.

And the discussion here: http://api.jquery.com/html/ (this explains that this isn't in jQuery core and why some logical solutions won't work)

Michael Dodd
  • 10,102
  • 12
  • 51
  • 64
Jamie Wong
  • 18,104
  • 8
  • 63
  • 81
  • why don't to use `wrap`? It is cleaner, I think – fl00r Apr 07 '11 at 21:35
  • 6
    Because using wrap actually affects the DOM tree displayed to the user. This doesn't. – Jamie Wong Apr 07 '11 at 21:37
  • I'm being thrown by the $("
    ") selector. I am accustomed to seeing $('div'), but not with the brackets and such. Can you, or someone, explain to me what that is doing? Also, it is desirable not to add it to the DOM, but, again, I'm confused why it doesn't. I think if I understood the first part, I'd understand why. Can anyone explain?
    – Steve C. Mar 24 '14 at 18:57
  • 2
    @SteveC. "
    " isn't a selector here. `$("
    ")` constructs a new div element. See: http://api.jquery.com/jQuery/#jQuery2
    – Jamie Wong Apr 01 '14 at 03:50
6

You could try this:

var html = $('<div>').append($('#example').clone()).html();
phixr
  • 486
  • 4
  • 8
2

For browsers that support it, outerHTML can do that. There are jQuery plugins like this and this that enable support via some clever jQuery.

Dominic Barnes
  • 28,083
  • 8
  • 65
  • 90
-2
var outerHtml = $('#example').detach();
-4

Anything wrong with simply using $('#example') ? This grabs the whole thing!

ben
  • 1