dev.e.loper
dev.e.loper

Reputation: 36044

Getting html from jQuery object

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

Upvotes: 0

Views: 229

Answers (4)

Denis Kozhukhov
Denis Kozhukhov

Reputation: 11

I do it like the following:

var containerObj = $ ('<div>');
var buildObj = $ ('<img>', { src:imgSrc });
$ (containerObj).append (buildObj);
var selection = $(containerObj).html();

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630429

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.

Upvotes: 2

sje397
sje397

Reputation: 41822

.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()

Upvotes: 2

JD Courtoy
JD Courtoy

Reputation: 2963

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.

Upvotes: 1

Related Questions