Artur Sapek
Artur Sapek

Reputation: 2507

Adding Javascript objects into innerHTML

Say I create an image object like below. ( create(); is a function I wrote but I know this function works.)

var img = create("img", "images/duba.jpg");

When I try to put this image into the innerHTML of another object that's a div, I get this plain text where the image should show up:

[object HTMLImageElement]

What's the correct method to insert one object into another like this? I have to think there's a more graceful method than hard-coding the innerHTML with strings, which I've tried successfully.

Upvotes: 1

Views: 12674

Answers (5)

FishBasketGordo
FishBasketGordo

Reputation: 23142

Use the appendChild method. The innerHTML property receives a string, not a DOM element.

https://developer.mozilla.org/En/DOM/Node.appendChild

Upvotes: 1

Ruan Mendes
Ruan Mendes

Reputation: 92294

If you are creating an element you can't set it as a node's innerHTML, that takes a string of HTML. Just use DOM manipulation

parent.appendChild ( create("img", "images/duba.jpg") );

Upvotes: 1

Daveo
Daveo

Reputation: 1225

I think you need to use:

otherObject.appendChild(img);

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816700

You should use DOM manipulation methods. E.g.

Upvotes: 1

SLaks
SLaks

Reputation: 887657

Call appendChild to append the DOM element to an existing element.

Upvotes: 3

Related Questions