Svish
Svish

Reputation: 157981

How to display the HTML of an image

Say I have an image like this:

<img src="someimage.png" alt="Image" />

I want to display the html of that image in for example a code tag, but how can I get it? I can get the image easily:

$('img');

But how can I get the HTML of it and append it to a code tag?

Upvotes: 3

Views: 132

Answers (2)

Stefan Kendall
Stefan Kendall

Reputation: 67802

Plugin form:

jQuery.fn.outerHtml = function() {
    return $('<div>').append( this.clone() ).html();
};

$('#mycode').append($('img').outerHtml());

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630349

Say you have an element like this:

<code id="mycode"></code>

You can do it like this:

$("#mycode").append($("<div />").append($('img').clone()).html());

Or if you want it semi-encoded for display, like this:

var html = $("<div />").append($('img').clone()).html();
$("#mycode").append(html.replace('<','&lt;').replace('>','&gt'));​​​​​​​​​​​​​​​​​​​​​

You can give that a try here. The getting the html portion itself is available in plugin form as well, here and here, the encoding, if you need it, you'll have to do yourself, or get a syntax plugin.

Upvotes: 5

Related Questions