bestprogrammerintheworld bestprogrammerintheworld - 4 years ago 220
HTML Question

jQuery get image's HTML as string

How do I get the html of an image with jQuery?

I want this as the output:

<img src="pokerface.png" alt="pokerface" />

I'm trying with this, but I'm getting an empty string (or null):

var imageHtml = $("#user-dialog .product-item img").html();

The following returns the Object, but I want the html

var imageHtml = $("#user-dialog .product-item img")

How do I do that?

If I try with

var imageHtml = $("#user-dialog .product-item img").attr("src");

I get the correct source of the image (
), so I know it's the correct element.

Answer Source

If the image is the only element inside the container you could do this:

$("#user-dialog .product-item img").parent().html();  

Otherwise you can create a dummy element and append the img object to it to get the .html() value.

$('<div>').append($("#user-dialog .product-item img").clone()).html();  

The solution is proposed here
JQuery Object to String

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download