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 (pokerface.png
), so I know it's the correct element.
jQuery("#user-dialog .product-item img").get(0).outerHTML;
You're effectively looking for the outerHTML
(in those browsers that support it):
var imageHtml = $("#user-dialog .product-item img").map(function(){
return this.outerHTML;
}).get();
JS Fiddle demo.
This will, of course, return an array of the img
element's HTML; which allows jQuery to collate all the relevant information, rather than explicitly iterating through the matched set with get()
or using bracket-notation indices [n]
And a simple (seriously, it's very simple) plugin to retrieve the outerHTML
of the matched elements:
(function ($) {
$.fn.htmlOuter = function () {
var self = this,
len = self.length,
_tmp = document.createElement('div'),
_h = [];
for (var i = 0; i < len; i++) {
_tmp.appendChild(self[i].cloneNode());
_h.push(_tmp.innerHTML);
_tmp.innerHTML = '';
}
return _h;
};
})(jQuery);
var images = $('img').htmlOuter();
console.log(images);
JS Fiddle demo.
Note that the above returns an array, whereas, ordinarily, jQuery getters return results from only the first element of a matched set, if that's what you'd prefer then you could alter the final line of the plugin to:
return _h[0];
JS Fiddle demo.
Oh, and obviously (like .text()
and other getter methods) this explitly cannot be chained, given that it returns an array, or a string (if you preferred), not the jQuery object.
References:
get()
.map()
.Array.push()
.document.createElement()
.Node.appendChild()
.Node.cloneNode()
.outerHTML
.outerHTML
compatibility.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
How do you convert a jQuery object into a string?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With