skip to Main Content

I don’t know why it gives me this Error:
Uncaught ReferenceError: button is not defined

even though there is obviously a definition for "button", right?
I had the "const button =…"
but for some reason in tells me that i still don’t have an definition for button

var a = prompt("Whats the password?")
var anser = "You Beat Me!"

function myFunction() {
  document.createElement("BUTTON");
  button.classList += 'btn btn-success';
  const button = document.getElementByClassName("btn btn-success");
  var t = document.createTextNode("Next>>");
  button.appendChild(t);
  document.body.appendChild(button)
}

button.addEventListener("click", function() {
    // Functionality to be executed when the button is clicked
    alert("Button clicked!");
});
    
if (a === anser) {
    myFunction()
    const element1 = document.getElementById("btn1")
  element1.remove();
} else {
    alert("wrong! try again")
}

var a = "The password is - You Beat Me!"

function remove() {
  const element1 = document.getElementById("btn1")
  element1.remove();
}

function refreshPage(){
    window.location.reload();
}

2

Answers


  1. You are trying to do things on your button before having declared it.

    function myFunction() {
      document.createElement("BUTTON");
    // "button" isn't defined at that time
    //vvvvvvvvvvvvvvvv
      button.classList += 'btn btn-success';
      const button = document.getElementByClassName("btn btn-success");
    //^^^^^^^^^^^^
    // You're only declaring its existence *afterwards*
      var t = document.createTextNode("Next>>");
      button.appendChild(t);
      document.body.appendChild(button)
    }
    
    Login or Signup to reply.
  2. I think you didn’t define the button before you tried to modify it. Should look like this.

    function myFunction() {
      document.createElement("BUTTON");
      const button = document.getElementByClassName("btn btn-success");
      button.classList += 'btn btn-success';
      var t = document.createTextNode("Next>>");
      button.appendChild(t);
      document.body.appendChild(button)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search