5

I think I've read through the complete jQuery API documentation and looked at jQuery objects and simple DOM elements in the debugger to check what methods they actually have at runtime, but for the life of me, I can't find a way to get the html string that represents the contents of a jQuery object or a DOM Node. Am I missing something?

jQuery objects have the method html(), DOM elements have the property innerHTML but both only give the inner html of the object. So if I have HTML like this:

<body>
    <div>
        <p>Hello World!</p>
    </div>
</body>

And I use jQuery doing something like this var $div = $body.find("div") and I then call $div.html() the returned string is "<p>Hello World!</p>". But I'm looking for a way to make it return "<div><p>Hello World!</p></div>" (I don't care about the whitespace).

What am I doing wrong? It can't be that difficult to get the html representation of these objects, can it?

Joachim Kurz
  • 2,875
  • 6
  • 23
  • 43
  • possible duplicate of [How to get the innerHtml, including the tag, using jQuery?](http://stackoverflow.com/questions/2319213/how-to-get-the-innerhtml-including-the-tag-using-jquery) – epascarello May 09 '13 at 16:42
  • Duplicate: http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html – Niels May 09 '13 at 16:43

3 Answers3

8

try the dom property .outerHTML

Colleen
  • 23,899
  • 12
  • 45
  • 75
  • 2
    I remembered this as a non-standard IE specific thing, but it seems to be [widely adopted](https://developer.mozilla.org/en-US/docs/DOM/element.outerHTML) by now. – vinczemarton May 09 '13 at 16:46
2

You can use the '.outerHTML' property. This is how it would look using jquery: http://jsfiddle.net/MHvmm/

$('div')[0].outerHTML
Nate
  • 651
  • 4
  • 7
0

This is possible by enclosing your desired object in another object, and the fetching the innerHTML. It is explained in much more detail here: How do you convert a jQuery object into a string?

Community
  • 1
  • 1
Jan
  • 220
  • 1
  • 2
  • 8