简体   繁体   中英

How do you append elements to a div?

I'm making a little game based on tiles and want to make a function that adds the tiles with their tags already applied.

This is my code with tileDIV being an ID and cols being a float:

function createTiles() {
    let a = document.createElement("img")
    a.src = "tiles/0.png"
    for (let i = 0; i < cols; i++) {
        tileDiv.appendChild(a)
    }
}

When I execute this function, nothing happens.

define the tileDiv using DOM before calling it,

var tileDiv = document.getElementById("tileDiv");

also col is not defined, so you have to define it too for your loop function

First off, titleDiv isn't defined anywhere in the script. You should define it before appending a child to it. Cols isn't defined either, that is also why it's not working.

function createTiles() {
let titleDiv = document.querySelector('.whateverdivis');
let a = document.createElement("img")
a.src = "tiles/0.png"
for (let i = 0; i < cols; i++) { //what and WHERE is cols? 
    tileDiv.appendChild(a)
}
}
createTiles(); //call your function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM