Reputation: 496
I am trying to make a generic function that removes anything that calls it. My code is as follows:
function deletethis(n){
//n is unused in this shortened snippet
this.parentNode.removeChild(this);
}
<button onclick="deletethis(5)">Click to remove</button>
Expected behaviour: the button gets removed.
Actual behaviour: Error Cannot read property 'removeChild' of undefined
Upvotes: 0
Views: 433
Reputation: 416
You can make use of events also,
function deletethis(event) {
event.currentTarget.remove();
}
<button onclick='deletethis(event)'>hello</button>
Upvotes: 0
Reputation: 5250
As James pointed out in the comments. this
doesn't get passed automatically. Try this
function deletethis(ele, n){
//n is unused in this shortened snippet
ele.parentNode.removeChild(ele);
}
<button onclick="deletethis(this, 5)">Click to remove</button>
Upvotes: 2
Reputation: 22227
Don't use in-line event listeners and this
will be set properly:
function deletethis(n){
this.parentNode.removeChild(this);
}
document.querySelector("button").addEventListener("click", deletethis);
<button>Click to remove</button>
Upvotes: 1
Reputation: 74
Just pass the ID to this function, and it should work :)
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
Upvotes: 1