JQuery get HTML image as string
How to get html images using jQuery?
I want this as a conclusion:
<img src="pokerface.png" alt="pokerface" /> I try with this, but I get an empty string (or null):
var imageHtml = $("#user-dialog .product-item img").html(); Next comes Object , but I want html
var imageHtml = $("#user-dialog .product-item img") How to do it?
If I try with
var imageHtml = $("#user-dialog .product-item img").attr("src"); I get the correct image source ( pokerface.png ), so I know it as the right element.
If the image is the only element inside the container, you can do this:
$("#user-dialog .product-item img").parent().html(); Otherwise, you can create a dummy element and add an img object to it to get the .html () value.
$('<div>').append($("#user-dialog .product-item img").clone()).html(); The solution is proposed here.
How to convert jQuery object to string?
jQuery("#user-dialog .product-item img").get(0).outerHTML; Are you really looking for outerHTML (in those browsers that support it):
var imageHtml = $("#user-dialog .product-item img").map(function(){ return this.outerHTML; }).get(); This, of course, will return an array of the HTML img element; which allows jQuery to collect all relevant information, instead of explicitly iterating through a consistent set using get() or using note indices [n]
And a simple (seriously, very simple) plugin for getting outerHTML consistent 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); Note that the above returns an array, whereas, as a rule, jQuery recipients return results only from the first element of the matched set, if this is what you prefer, then you could change the final plugin string to:
return _h[0]; Oh, and obviously (like .text() and other getter methods), this obviously cannot be encoded if it returns an array or string (if you prefer), rather than a jQuery object.
Literature:
- JQuery:
- "Normal" JavaScript: