M.Taki_Eddine
M.Taki_Eddine

Reputation: 160

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>

Upvotes: 4

Views: 582

Answers (2)

Vahid Farahmandian
Vahid Farahmandian

Reputation: 6568

All you need to do is to rename your function and avoid using remove as its name(The reason for this is included in @Pointy's answer). Try this:

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

</script>

Upvotes: 2

Pointy
Pointy

Reputation: 413767

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

Upvotes: 4

Related Questions