5

Working on my Project for class, and I have came across an issue. I debugged the issue, but I'm unsure why it happens. The issue seem to only limit the img showed to two all the time during the process of creating the table. ie

<tr><td>img</td><td>img2</td></tr>
<tr><td></td><td>img2</td><td>img</td></tr>

It removes the first img and append it to the created cell. Sorry if I'm not making any sense, I will provide a snippet of the code.

var ImgSrcB = document.createElement("img");
ImgSrcB.src = "Black.png";
var ImgSrcW = document.createElement("img");
ImgSrcW.src = "White.png";
var body = document.body, tbl = document.createElement('table');
tbl.style.width = 50*8;
tbl.style.height = 50*8;
for (var i = 0; i < 8;i++) {
    var tr = tbl.insertRow();
    var td;
    for (var j = 0; j < 8; j++) {
        if (i%2 == 0) {
            if (j % 2 == 0) {
                td = tr.insertCell();
                td.appendChild(ImgSrcB);
            }
            else if (j %2 == 1) {
                td = tr.insertCell();
                td.appendChild(ImgSrcW);
            }
        }
        else if (i % 2 == 1) {
            if (j % 2 == 0) {
                td = tr.insertCell();
                td.appendChild(ImgSrcW);
            }
            else if ( j % 2 == 1 ) {
                td = tr.insertCell();
                td.appendChild(ImgSrcB);
            }
        }
        console.log(i, j); //Debug Purposes
    }
}
body.appendChild(tbl);

Any idea why this happens? Do I have a wrong understanding on appendChild?

1 Answer 1

4

You create one image, and then append it everywhere. When you append a DOM node that's already found on the DOM, it will be removed from the old location, and appended to the new location, hence you're seeing the same instance of image moving around (or rather, you just see it in its final place according to the loop).

You need to create a new instance of the correct image for every iteration of the loop, and append that.

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

2 Comments

Man, That make me feel dumb. It obvious now you say it. Thank you.
@Lerucelulu Don't be, it's a known gotcha that's not very clear by the verb "to append". Good luck! :)

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.