0

I have a html and javascript script that makes tic tac toe when trying to make an array of the buttons but getElementById() returns null when making the array html:

<!DOCTYPE html>
<head>
    <title>tic tac toe</title>
    <script src="javas.js"></script>
</head>
<body>
    </body>

javascript:

player = 1
btns = [[],[],[]]
i = 0
for (y = 0;y<3;y++){
  for (x = 0;x<3;x++){
    i++
    btn = document.createElement("button");btn.innerText="-";btn.onclick=clicked()
    btns[y].push(btn)
    document.body.appendChild(btn);
  }
  document.body.appendChild(document.createElement("br"));
}
function clicked(){
  for (y = 0;y<3;y++){
    for (x = 0;x<3;x++){
      if(btns[y][x].innerText != "-"){
        if(player == 1){
          btns[y][x].innerText = "x"
        }
        else{
          btns[y][x].innerText = "o"
        }
        if(player==2){
          player = 0
        }
        player++;
      }
    }
  }
}

I have tried logging I and the return of getElementByID()

  • 2
    You cannot have spaces in id values, and you cannot fetch elements by id before the DOM has been constructed. – Pointy Apr 12 '23 at 19:09
  • `getElementById` is not for getting the element ID. It’s for getting the element when you already know the ID. – user3840170 Apr 12 '23 at 19:45

0 Answers0