1

this is my problem: im trying to create an image selector, i mean a collection of images shown on the screen among which i can choose one and store it in a var. This is the code for the array:

<script typre="text/javascript">
    var img = new Array();
    img[0] = new Image();
    img[0].src = "../images/poggiatesta2.jpg";
    img[1] = new Image();
    img[1].src = "../images/poggiatesta1.JPG";

    for (var i = 0; i < img.length; i++) {
        document.write(img[i]);
    };

</script>

When i run it, it displays [object HTMLImageElement] instead of the image! What should i do?? Thanks all!

1

3 Answers 3

2

Because img[i] is an object and document.write will write it as string representation of it by calling img[i].toString().

If you want to display an image then use

for (var i = 0; i < img.length; i++) {
        document.body.appendChild(img[i]);
};
Sign up to request clarification or add additional context in comments.

Comments

1
var img = new Image(); 
img.src = "../images/poggiatesta2.jpg"; 
document.write(img.outerHTML);

Use the outerHTML property in order to display it

Comments

0

It is obvious because for loop will print img[0],img[1] not src of image You can write img[i].src

 var img = new Array();
        img[0] = new Image();
        img[0].src = "../images/poggiatesta2.jpg";
        img[1] = new Image();
        img[1].src = "../images/poggiatesta1.JPG";
    
        for (var i = 0; i < img.length; i++) {
            alert(img[i].src);
        }; 

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.