var selectedLetter = "global right now";
function GetLink() {
  fetch("https://random-word-api.herokuapp.com/word")
    .then(
      r => {
        if (r.status != 200)
          return;
        r.json().then(
          c => {
            for (let i = 0; i < c[0].length; i++) {
              p = document.createElement("div");
              p.innerHTML = "_";
              if (i == 0) {
                p.setAttribute("id", "first");
              }
              p.classList.add("word");
              document.querySelector("#word").appendChild(p)
            }
          });
      }
    )
}
function SetupKeyboard() {
  letters = document.getElementsByClassName("word");
  selectedLetter = document.getElementById("first");
}
window.addEventListener('load', () => {
  GetLink();
  SetupKeyboard();
});html,
body,
#wrapper {
  height: 100%;
  width: 100%;
}
#title {
  font-size: xx-large;
  text-align: center;
}
#word {
  font-size: xx-large;
  text-align: center;
}
.word {
  display: inline;
  margin: 2px;
  background-color: beige;
}<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Hangman</title>
  <link rel="stylesheet" href="style.css">
  <script src="index.js"></script>
</head>
<body>
  <div id="title">
    Hangman
  </div>
  <div id="word">
  </div>
</body>
</html>It seems to be a simple problem but it's driving me insane.
function SetupKeyboard()
{
  letters=document.getElementsByClassName("word");    
  selectedLetter=document.getElementById("first");
}
I need the selected letter to be the first element of the "letters" array but for some reason selectedLetter=letters[0] gave back "undefined". I tried this approach too and it's the same problem. I am obviously missing something.
When I debug the code it works properly and the console logs everything as expected. When NOT in debugger the value of selectedLetter is "undefined". Also, the problem is gone when I call the function manually through browser console as well.
I know the problem is not in the DOM not existing because I run it all like this:
window.addEventListener('load', ()=>{
    GetLink();
    SetupKeyboard();
});
 
     
    