Delete button removes itself instead of target element

I really have a problem that I cannot understand.

I have divone that contains 2 paragraphs and a clickable button to delete the first element p, but it is strange that the button deletes it and the element pcontinues to live!

This is the result of my code:

Code result

But when I click on the button, I get the following:

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>
+4
source share
2 answers

The name of the remove function is hidden by the built-in remove method on the button element itself. If you change the name, it will work as expected.

, HTML onfoo, , ( ) DOM node . , JavaScript addEventListener().

+4

, , remove ( @Pointy). :

<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>
+2

All Articles