0

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

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 - you'd probably want to do the clone as suggested by Nick Craver in that case, so the element doesn't get moved
2

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.

1 Comment

a variation of my first suggestion - and a very clean implementation
1

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.

Comments

1

I do it like the following:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.