Shpigford
Shpigford

Reputation: 25348

jQuery: Get HTML including the selector?

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.

Upvotes: 40

Views: 34144

Answers (5)

Jamie Wong
Jamie Wong

Reputation: 18350

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)

Upvotes: 57

ben
ben

Reputation: 1

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

Upvotes: -4

Andrey Popov
Andrey Popov

Reputation: 33

var outerHtml = $('#example').detach();

Upvotes: -2

phixr
phixr

Reputation: 486

You could try this:

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

Upvotes: 6

Dominic Barnes
Dominic Barnes

Reputation: 28429

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

Upvotes: 2

Related Questions