0

I just want a for loop to print the same image 10 times without manually creating 10 's since I may want to append more later. I have used this exact same code in other projects and it has worked but for some reason it won't work this time.

The image html is:

<img id = "crate" src="img/Acrate.png"/>

Here's my code:

function drawCrates (){
                        for(i = 0; i < 10; i++){
                            var crate_img = document.createElement("IMG");
                            crate_img.setAttribute("src", "images/Acrate.png");
                            document.getElementById("crate").appendChild(crate_img);
                        }
}
drawCrates();
3
  • 2
    you should append elements to those element which can contain other elements. Like you can append all the images to a div. Commented Jan 11, 2015 at 6:17
  • 2
    change that #crate element to a div and this will work Commented Jan 11, 2015 at 6:18
  • thanks, it worked! Appending it to the div worked. Commented Jan 11, 2015 at 6:21

2 Answers 2

2

You need to append the image element to such element that can hold other elements. Try this,

HTML :

<div id="imageDiv">
</div>

javaScript :

function drawCrates (){
    for(i = 0; i < 10; i++){
        var crate_img = document.createElement("IMG");
        crate_img.setAttribute("src", "https://lh5.googleusercontent.com/-PfTrZFQ8c4U/AAAAAAAAAAI/AAAAAAAAAA0/IJXxoIqKNSU/photo.jpg");
        document.getElementById("imageDiv").appendChild(crate_img);
    }
}
drawCrates();

jsFiddle

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

Comments

2

I would suggest using a DocumentFragment for speed, and then just cloning the node as you need it. The code looks like the following:

function drawCrates (){
    var fragment = document.createDocumentFragment(),
        img = document.createElement('img');

    img.setAttribute("src", "images/Acrate.png");
    fragment.appendChild(img);
    for(i = 0; i < 9; i++){
        fragment.appendChild(img.cloneNode(true));
    }

    document.body.appendChild(fragment);
}
drawCrates();

Your issue stems from trying to append an element as a child of an <img> element, which is invalid. The code you have:

<img id="crate" ... />

When you run the code document.getElementById("crate") you are grabbing the <img> element, and it is not possible to append child elements to an <img>.

1 Comment

This doesn't really address the issue of why appending to a img tag doesn't work.

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.