Payam
Payam

Reputation: 3

Cant figure out how to fix uncaught TypeError.

I keep getting a message saying uncaught type error "Cannot set property 'innerHTML' of null"

Im trying to create a sokoban game with html/css/javascript. The gameboard is where im running into issues, it's not displaying no matter what I do. The code seems fine to me

Ive been trying to fix it for the past hour but I really dont know what im doing wrong.

here is my code :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Sokoban</title>
    <meta name="description" content = "The Sokoban Game">
    <meta name="author" content="PHP Class">

    <link rel="stylesheet" href="sokobanstyling.css"> 


</head>

<body>
    <h1>Sokoban</h1>

    <input type="text" id="txtUsername" placeholder="Your name here"/>
    <button onclick="printBoard()">Press ME</button>

<script>


var gBoard = buildBoard ();  

function buildBoard () {
    var board = new Array(6); 

    for (var i=0; i<board.length; i++){
        board[i] = new Array(5); 
    }

   for (var i=0; i<board.length; i++) {
       for (var j=0; j<board[0].length; j++){
           if (i == 0 || i == board.length-1 || j == 0 || j == board[0].length-1) {
               board[i][j] = "WALL"; 

           } else {
               board[i][j] = "FLOOR"; 
           }
        }
    }

    console.log(board);
    return board; 
}

function printBoard() {

    var tblBoard = document.getElementById('tblBoard'); 
    var strHTML = ''; 
    for (var i=0; i<gBoard.length; i++){
        console.log(gBoard[i]); 
        for (var j=0; j<gBoard[0].length; j++) {
            strHTML += "<td>A"; 
            /*
            if (gBoard[i][j] == "WALL") 
            } else if (gBoard[i][j]=="WALL") {

            }
            */
            strHTML += "</td>"; 
        }
        strHTML += "</tr>"; 
    }

    tblBoard.innerHTML = strHTML; 
}


</script>




</body>
</html>

Upvotes: 0

Views: 58

Answers (1)

Dakota Raymond
Dakota Raymond

Reputation: 135

You are trying to get an element by Id that doesn't exist

var tblBoard = document.getElementById('tblBoard'); 

Then trying to access the innerHTML of this

tblBoard.innerHTML = strHTML; 

Set the id of whatever element you are wanting to modify there with id="tblBoard"

Upvotes: 2

Related Questions