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:
- jQuery:
- 'Plain' JavaScript: