'Code stops working when I add a function call but works when I remove the call

This code works. It changes the button color without any problem


   document.addEventListener("keypress", function(event) {
        if (event.keyCode == 49) {
     

      button1.style.backgroundColor = "lightgreen";
     
      setTimeout(() => {
       button2.style.border = "";
       button1.style.backgroundColor = "";
          
          console.log("changed style ")

      }, 100);
      getDate();
   }

But when I add socket.Emit("hello","world") It throws the error "getting TypeError: Cannot read properties of null (reading 'style')" it can no longer change the color of button1.


  document.addEventListener("keypress", function(event) {
        if (event.keyCode == 49) {
      socket.emit("hello" , "world") <= When this is added

      button1.style.backgroundColor = "lightgreen"; <= Error is caused by this line
     
      setTimeout(() => {
       button2.style.border = "";
       button1.style.backgroundColor = "";
          
          console.log("changed style ")

      }, 100);
      getDate();
   }


Solution 1:[1]

Button1 is not being defined thus it cannot apply a style to it. Please provide more code or look back and properly define it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DrakoHyena