views:

73

answers:

2

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?

+5  A: 

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.

Nick Craver
Why are you wrapping the <img/ in the div? It seems like he's trying to just output the html and append it to the codetag.
Stefan Kendall
@Stefan - `.html()` gets the *innerHTML*, of which there is none :)
Nick Craver
Ah, you needed a parent to make the html content be of the element itself. This seems like a hack workaround that should exist in plugin form.
Stefan Kendall
@Stefan - There are plugins that do *exactly* this :) Search for `outerHTML` if you want it in plugin form...and I agree if you're using it more than once, go that route.
Nick Craver
In my opinion this should be in the core, but I guess others don't agree since it's not there already.
Svish
A: 

Plugin form:

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

$('#mycode').append($('img').outerHtml());
Stefan Kendall
Yes, that gives me nothing because the `html` function returns the inner html, which of course is nothing for an `img`.
Svish
Updated to phrase Nick's answer in plugin form, so it's re-usable.
Stefan Kendall
@Stefan - The plugin form exists many places, no need to replicate it, and `$(this)` is redundant if you must do it :)
Nick Craver
@Nick Craver: I task you with re-reading the founding purpose of stack overflow. Just because it's on expert-sexchange doesn't mean it shouldn't be here.
Stefan Kendall
@Stefan - I agree, though this is *many* places on the web was more my point. My other was just saying if you're posting a plugin as an example, have it as correct as possible :) `$(this)` is cloning the jQuery object as well, just `this.clone()` is much more efficient/less wasteful :)
Nick Craver
Ah, you could have edited my post to make it more correct. I've updated my answer. Who knows, $(this) vs this in a tight inner loop might cause IE to stop responding due to an excess of operations. I've seen weirder things.
Stefan Kendall