I’m using the jQuery .html() method to add images to a div in my webpage dynamically when I user clicks on the event that image belongs too.
I’ve confirmed that the image tag is properly formatted when returned to the server, but once inserted using .html(), the ending portion of the tag is lost.
For example, what was originally
<img src="poop.txt"></img>
Comes out as being
<img src="poop.txt">
on the actual webpage. What is the cause of this? .html() works perfectly with a set of spans that I’m inserting in a similar fashion on another page on the site, but when it comes to image tags, it fails.
The problem (actually it’s a safe-guard and a benefit) is that JavaScript, and therefore jQuery, creates only valid HTML. As the
imgtag has no closing tag (since it can’t have any content, it self-closes) it isn’t appended to the web-page.References:
imgelement, Mozilla Developer Network.