0

Can anyone explain why this piece of code will remove the buton after click in FF and Chrome? IE will show an alert.

<html>
<head>
<script>
function remove()
{
alert('test');
}

</script>
</head>
<body>
<input type="button" onclick="remove();" value="Remove"/>
</body>
</html>
j08691
  • 204,283
  • 31
  • 260
  • 272
  • 3
    Don't name functions after JavaScript methods or events. – j08691 Jul 09 '14 at 17:01
  • [Don't use inline event handlers](http://stackoverflow.com/a/21975639/218196) or at least know what you are doing. [DOM nodes have a `remove` method](https://developer.mozilla.org/en-US/docs/Web/API/ChildNode.remove) and that's what is getting called, not your function. – Felix Kling Jul 09 '14 at 17:02
  • 1
    @FelixKling - thanks. I knew there was a question just like this in here somewhere from seeing it before. Finding it took a little work, but my OCD feels better now. – j08691 Jul 09 '14 at 17:17

3 Answers3

1

Because javascript has a remove method. Name your function abcd and it is fine:

<html>
<head>
<script>
function abcd()
{
alert('test');
}

</script>
</head>
<body>
<input type="button" onclick="abcd();" value="Remove"/>
</body>
</html>
Claudiu Creanga
  • 8,031
  • 10
  • 71
  • 110
1

Don't use inline event handlers or at least know what you are doing.

The problem is that the properties of the element itself are in the scope of the inline event handler, and DOM nodes have a remove method *****. So remove() is equivalent to this.remove(), i.e. it calls the remove method of the button.

Solutions:


*: This is a relatively new API which is not supported by IE yet, so it works fine in IE.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

using inline event handlers is usually considered bad practice, as you are asking the browser to parse javascript events from html strings, a much better way would be as follows:

<html>
<head>
<script>
  window.addEventListener("load",function(){
    window.myButton = document.getElementById("myButton");
    window.myButton.addEventListener("click",myButtonFunction);
  });

  function myButtonFunction()
  {
    alert('test');    
  }

</script>
</head>
<body>
<input id="myButton" type="button" value="Remove"/>
</body>
</html>

also you don't need to declare it as a window variable (global), unless you want to access it in your function. (but could also access it again via document.getElementById("myButton")

dano
  • 1,043
  • 1
  • 6
  • 11