Reputation: 108500
Is there a good way of printing out a jQuery object as pure HTML?
ex:
<img src="example.jpg">
<script>
var img = $('img').eq(0);
console.log(img.toString());
</script>
toString()
doesn't work this way. I need the HTML equivalent string , i.e:
<img src="example.jpg">
Upvotes: 23
Views: 50871
Reputation: 14967
If you need to print the object in HTML format, use this extension outerHTML or this outerHTML.
Update
Update the link and include the code for second link:
$.fn.outerHTML = function(){
// IE, Chrome & Safari will comply with the non-standard outerHTML, all others (FF) will have a fall-back for cloning
return (!this.length) ? this : (this[0].outerHTML || (
function(el){
var div = document.createElement('div');
div.appendChild(el.cloneNode(true));
var contents = div.innerHTML;
div = null;
return contents;
})(this[0]));
}
Upvotes: 7
Reputation: 1247
$('img')[0].outerHTML
will give you the HTML of the first img on the page. You will then need to use a for loop to get the HTML of all the images, or put an ID on the image and specify it only in the jQuery selector.
Upvotes: 27
Reputation: 28810
You could wrap it and then use html:
var img = $('img').eq(0);
console.log(img.wrap("<span></span>").parent().html());
Upvotes: 16