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();
});
document.createElement("button2")button? Are you trying to create an element with abutton2tag or abuttonwith an id ofbutton2?Why?Because you're trying to access.removeofnull, 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?