Christian Skoog
Christian Skoog

Reputation: 1

How to display a js object's property image in a div?

I would like to display the image property of an object written in Javascript. I have tried to use the following code, but it doesn't want to work for me. The function show_image is from here, so I know it works (it works when I try it with a 'raw' image file as well.) I also wish to be able to choose where, within a certain div, this image should show up. How would I go about doing this? The div I wish to append it too can be identified by it's classname I guess, and I think I should use "getElementById", but exactly how I would do this is a mystery.

The image does show up as an empty square, but it says "[object%20HTMLImageElement]".

Here's my current scriptcode:

var img = new Image();
    img.src = 'imagehere';

    card=new Object();
    card.backImage=img;
    card.height=100;
    card.width=100;

    show_image(card.backImage, 
                     276, 
                     110, 
                     'Whateverthenameis');

    function show_image(src, width, height, alt) {
        var img = document.createElement("img");
        img.src = src;
        img.width = width;
        img.height = height;
        img.alt = alt;

        document.body.appendChild(img);
    }

Thanks in advance!

Upvotes: 0

Views: 619

Answers (1)

Paul S.
Paul S.

Reputation: 66364

The thing that attaches the created Image to the DOM is Node.appendChild. In your example, you're using document.body.appendChild(img);, so this is the line that you'd need to change. You may also want to add another parameter to your function, to let you pass the Node you want the image appended to, too.

For example, your resulting function may have the form

function show_image(src, width, height, alt, parent) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    parent.appendChild(img);
}

and invoked by

show_image(
    'http://yummy.p.ie/photo.jpg',      // url
    100, 100, 'PIE!',                   // width, height, alt
    document.getElementById('pieShelf') // parent
);

With some HTML that looks like

<div id="pieShelf">Look at my yummy pie</div>

Upvotes: 1

Related Questions