M.Taki_Eddine M.Taki_Eddine - 3 months ago 7x
Javascript Question

A deleting button deletes itself instead of the targeted element

I got a really bothering problem which I can not understand.

I have a

which contains 2 paragraphs, and a clickable button to delete the first
element, but the strange thing is that the button deletes it self and the
element continues to live!

This is the result of my code:

Code's result

But when I click on the button I get this:


Below is my code:

<p id="id_1">The first paragraph.</p>
<p id="id_2">The second one.</p>
<button onclick="remove(document.getElementById('id_1'));">click me!</button>
function remove(elem)
var parent=elem.parentNode;



The function name "remove" is being hidden by the native "remove" method on the button element itself. If you change the name, it works as expected.

Event handlers established with HTML "onfoo" attributes execute in a specially-constructed scope that includes the methods (and other properties) on the DOM node for the element. That's just one of many reasons that it's preferable to use JavaScript to attach event handlers via addEventListener().