M.Taki_Eddine M.Taki_Eddine - 5 months ago 8
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

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

This is the result of my code:

Code's result

But when I click on the button I get this:

onclick

Below is my code:

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

</script>

Answer

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().

Comments