Monday, March 25, 2019

JavaScript: Duplicate element IDs and duplicate function names


Consider this piece of code:

<html>
<body>
<button id='btn'>Button1</button>
<script>
  var bn1 = document.getElementById('btn');
  bn1.addEventListener('click', func);
 
  function func() {
    alert('func 1');
  }
</script>
<br>
<button id='btn'>Button2</button>
<script>
  var bn2 = document.getElementById('btn');
  bn1.addEventListener('click', func);
 
  function func() {
    alert('func 2');
  }
</script>
</body>
</html>


After this is loaded in a web browser, 2 buttons are displayed. When clicking on Button1, it will show both alerts "func 1" and "func 2". When clicking on Button 2, nothing will happen.

When there are multiple elements with the same ID, document.getElementById() always gets the same element.

Although 2 functions have the same name, they are different function entities and they are registered as different listeners for the target node. The name of the function is not important after addEventListener() is called.

No comments:

 
Get This <