0

Example:

var html_string = '<img src="http://www.example.com/image.jpg" />'
$(html_string).html()

produces:

'' // an empty string

Would expected that I'd get back the original HTML string in html_string.

What's going on? How can I get an the results I expected?

Dmitry Minkovsky
  • 36,185
  • 26
  • 116
  • 160

2 Answers2

4

.html() gives you the inner html of an element, since <img> elements are null/empty they have no inner html therefore you get an empty string.
What you want is the outer html

$(html_string)[0].outerHTML
Musa
  • 96,336
  • 17
  • 118
  • 137
  • Thanks Musa! Do you know how compatible outerHTML is? It's a standard DOM/JS API property not wrapped in jQuery... and I'm generally nervous using such unmitigated properties – Dmitry Minkovsky Jun 14 '13 at 04:33
  • Matt Ball's comment above addresses my concern: http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html – Dmitry Minkovsky Jun 14 '13 at 04:35
  • Per that link, best way to do it seems to be with `.clone().wrap('

    ').parent().html()`. I was trying to do that! But had missed the `.clone()` :D

    – Dmitry Minkovsky Jun 14 '13 at 04:37
2

The jQuery .html() returns the HTML code inside the selected DOM element, but not the element's HTML. That is why you are getting an empty string, because there is no HTML inside your image element. jQuery doest not provide a solution for this, but you can use outerHTML at the DOM element (not the jQuery one). If you want to do this with jQuery, create an element, put the one you want inside of it, and then use .html(). Look:

var string = '<img src="a.jpg"/>';
var $el = $(string);

var $wrapper = $('<p>').append($el).html();

Hope I've helped.

Walter Macambira
  • 2,574
  • 19
  • 28