Reputation: 76
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();
});
Upvotes: 0
Views: 5144
Reputation: 568
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();
});
Upvotes: 1