0

I am trying to remove a button after it is clicked (the button was created in javascript) and from a different post it said this code would work, but in my console i get the error:

Uncaught TypeError: Cannot read property 'remove' of null
at HTMLUnknownElement.<anonymous> (RBrOJeLwYgRM:335)

Why? Help! Code:

Code that is supposedly going to remove elements:

Element.prototype.remove = function() {
    this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
    for(var i = this.length - 1; i >= 0; i--) {
        if(this[i] && this[i].parentElement) {
            this[i].parentElement.removeChild(this[i]);
        }
    }
}

My code which activates the remove function:

else if (PaintBrush.crashWith(Finish)) {
      PaintBrush.y = 50;
      var button = document.createElement("button2");
button.innerHTML = "Level 2";
      var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
      GameArena.clear();
      GameArena.stop();
      button.addEventListener ("click", function() {
  startGame2();
        document.getElementById("button-2").remove();
});
2
  • Are you trying to remove the document.createElement("button2") button? Are you trying to create an element with a button2 tag or a button with an id of button2? Commented Feb 24, 2017 at 21:02
  • Why? Because you're trying to access .remove of null, just like the console error says. where are you calling .remove(), what are you calling .remove() on, and why do you think it might be null? Commented Feb 24, 2017 at 21:04

1 Answer 1

1

Try these changes

PaintBrush.y = 50;
var button = document.createElement("button"); //  remove the "2"
button.innerHTML = "Level 2";
button.id = "button-2";  // add the id to the button
document.body.appendChild(button); // append to body
GameArena.clear();
GameArena.stop();
button.addEventListener ("click", function() {
  startGame2();
  document.getElementById("button-2").remove();
});
Sign up to request clarification or add additional context in comments.

2 Comments

Works! Thanks! Really helpful, i had named it button2 because i had some css to position it, but creating a css id called button-2 and styling that works aswell. Thanks again!
Glad it helped, If you want to keep the "button2" class, you cand add it also, just use: button.className = "button2";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.