0

I'm trying to understand how to get the HTML contents including the parent selector. I know that the following will get me the HTML contents:

$obj.html();

(where $obj is a reference to my DOM object)

But what if I want the HTML contents including the parent selector? For example, let's say I have this code:

<div id="sample" class="something">
  <div class="inner"></div>
</div>

If I do:

$('#sample').html();

...I will get:

<div class="inner"></div>

But what I really want retuned is this:

<div id="sample" class="something">
  <div class="inner"></div>
</div>

Any ideas?

Andrew
  • 2,691
  • 6
  • 31
  • 47
  • possible duplicate of [Get selected element's outer HTML](http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html) – Jeff B Dec 19 '13 at 23:22

2 Answers2

3

While it's not standard - this works pretty much everywhere.

Use Element.outerHTML

var el = $obj[0]; // get the HTML element from the jQuery object
el.outerHTML; // the HTML including the outside bits

( fiddle )

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • Sounds good to me - when you say it's no standardm is it reliable? – Andrew Dec 19 '13 at 23:17
  • @Andrew I can't really say. Knowing the people involved in the decision process - I think it might get standardized eventually, and it certainly won't be removed from browsers. In practice - it's not going anywhere any time soon - the problem is the unspecified behavior in edge cases across browsers, but I'm yet to run into any edge cases myself. – Benjamin Gruenbaum Dec 19 '13 at 23:20
2

While it isn't completely standardized just yet, Element.outerHTML works in most browsers.

jsFiddle

document.querySelector('#sample').outerHTML;

Polyfills are available is earlier browser support is desired:

References

Daniel Imms
  • 47,944
  • 19
  • 150
  • 166