Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does creating a button in JavaScript code result in an error "Uncaught ReferenceError: button is not defined"?

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();
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading