4

I'm using jquery to both set html with an img tag and later retrieve html with an img tag and store it in a datastore.

When I initially set html, the string I'm passing in has a closing tag:

h += '<div class="photo">'
+ '<img src="' + msg + '" />'
+  '</div>';
$('#thumb').html(h);

When I retrieve the html later, it does not have a closing tag.
This is causing issues when I try serve this html at a later date.

$('div.thumbnail').html() 

produces html like this without the closing tag:

<div class="photo">
   <img src="http://lh3.ggpht.com/blah.jpg">
</div>

EDIT

Thanks for all the suggestions. In my case I kept getting an "expected </img>" error when trying to serve the HTML back.

So I changed my approach and used this code to retrieve the img src, rebuild the html, and then store it:

var xml = '<?xml version="1.0" encoding="utf-8"?>\n<content>\n';
var img = $("#thumbimage").attr("src");

xml += '<thumbURL><div class="photo"><img src="' + img +  '"/></div>'
    + '</thumbURL>\n';
cedarleaf
  • 153
  • 1
  • 8
  • possible duplicate of [jQuery.html() returns invalid IMG](http://stackoverflow.com/questions/4102744/jquery-html-returns-invalid-img) – Dr.Molle Aug 30 '11 at 22:10
  • If you serve the content correctly as HTML, then it should not generate any problem. [`img` elements don't have a closing tag](http://www.w3.org/TR/html4/struct/objects.html#edef-IMG). – Felix Kling Aug 30 '11 at 22:11
  • possible duplicate of [Jquery html() and self closing tags](http://stackoverflow.com/questions/2557295/jquery-html-and-self-closing-tags) – Felix Kling Aug 30 '11 at 22:12

2 Answers2

0

You should us jQuery a bit more to make it easier.

var content = $("<div>").addClass("photo").append($("<img>").attr("src", msg));
$("#thumb").html(content);

jQuery will build these tags for you. http://api.jquery.com/jQuery/#jQuery2

BZink
  • 7,687
  • 10
  • 37
  • 55
0

What problem is this causing specifically, to be honest i'd expect an unclosed img tag to render OK in all browsers.

.html() with no arguments is basically just a wrapper for .innerHTML, the results may vary by browser but it isn't a jquery issue

Paul Creasey
  • 28,321
  • 10
  • 54
  • 90