Home > Back-end >  Javascript image not populating in HTML table correctly
Javascript image not populating in HTML table correctly

Time:03-15

I am learning how to incorporate JavaScript into HTML and am trying to build a very simple web game based off a class project. (This is a sidebar, I successfully completed the project itself.)

I need two specific images to randomly populate the entire table. My code successfully creates the array of appropriate length and translates that correctly to the HTML, but the image sources don't seem to populate correctly. One image of each always shows up so I am confident my source paths are correct, and one of the images is always in the lower right hand corner, but the rest of the field is blank. When examining DevTools the array is there with appropriate img attributes but there is no source, except obviously on the img's that have a visible image.

class Field {

    static generateField(h, w, pct = .2) {
        let board = [];
        let tempArray = [];
        while (board.length < h) {
            while (tempArray.length < w) {
                const random = Math.random();
                if (random < pct) {
                    tempArray.push(imageB);
                } else {
                    tempArray.push(imageA);
                }
            }
            board.push(tempArray);
        }

        for (let a = 0; a < h; a  ) {
            let row = document.createElement("tr");
            for (let b = 0; b < w; b  ) {
                let cell = document.createElement("td");
                let img = document.createElement("img");
                img = board[a][b];
                img.style.width = "100%";
                img.style.height = "100%";
                cell.appendChild(img);
                row.appendChild(cell);
            }
            tblBody[0].appendChild(row);
        }
    }
}

The tblBody is defined outside the class. Originally my code was nested for loops and gave the exact same result.

Where am I going wrong?

CodePudding user response:

I'm assuming imageA and imageB are paths to image files. If so, your problem is here:

let img = document.createElement("img");
img = board[a][b];

You are assigning a newly created element object to img and then reassigning a string (the path to the image) to the same variable.

Instead, you have to add a source attribute to the img element you created, and set its value to the path for the image:

let img = document.createElement("img");
img.setAttribute("src", "<path to imageB>");

You can then append the img element, complete with its src attribute, to the cell.

  • Related