Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Img Table Creation Issue

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?

like image 909
Leruce lulu Avatar asked Sep 29 '22 03:09

Leruce lulu


1 Answers

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.

like image 98
Madara's Ghost Avatar answered Nov 01 '22 17:11

Madara's Ghost