tags:

views:

52

answers:

3

I'm constructing html element and putting it in jQuery object. I'm having trouble getting HTML out of that jQuery object. I thought I can just use .html() but that returns an empty string.

Ex:

var myImage = $("<img src='blah.gif' />");

then I want actually get that html

I tried $(myImage).html() <- no luck

A: 

Try $(myImage).get(0). That should return the DOM element you created.

You may need to actually add that jQuery object to the DOM first, somewhere, though.

JD Courtoy
+2  A: 

.html() will return the stuff inside the element it's called on.

if you're able to ensure the parent element only contains the image tag, you could call .html() on the parent.

another (ugly) option would be to set the content as data on the jquery object (i.e. obj.data(html_string)) and then retrieve it with .data()

sje397
Exactly correct. this would be the same for an element in the DOM. You can also create a dummy element: `$('<div />').append(myImage).html()`
Kobi
@Kobi - you'd probably want to do the clone as suggested by Nick Craver in that case, so the element doesn't get moved
sje397
+2  A: 

There are several variations of this around, it's typically called "outerHTML", something like this:

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

Then you can do this:

myImage.outerHTML(); //already a jQuery object, no need to re-wrap

You can try out a demo here, since .html() gets the HTML inside, we just take the element, clone it, stick it inside a temporary element and do .html() on that element instead.

Nick Craver
a variation of my first suggestion - and a very clean implementation
sje397