R
R
Rouzi2021-07-02 20:58:43
JavaScript
Rouzi, 2021-07-02 20:58:43

Why do I get an underfined error when I try to display the ID of a TD element?

I can't figure out what is wrong with this code:

var scene = document.getElementById("scene");
var gameArea = document.getElementById("gameArea");

function createMap(cols, rows){
    for(var i = 0; i < rows; i++){
        var rowBlock = document.createElement("tr");
        rowBlock.id = "block";
        gameArea.appendChild(rowBlock);
        for(var j = 0; j < cols; j++){
            var colBlock = document.createElement("td");
            colBlock.id = "cell";
            rowBlock.appendChild(colBlock);
        }
    }
}

createMap(5, 5);

var cells = document.querySelectorAll("#cell");


for(var i = 0; i < cells.length; i++){
    cells[i].addEventListener('click', function(){
        console.log(cells[i].id);
    })
}


When I click on a cell, instead of displaying the id, an error occurs

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question