0

'Overview: The error shows that btn.addEventListener isn't function.'

var btn= document.getElementsByTagName('button');
btn.addEventListener("click", function(){
      console.log('You Just Clicked !!');
});

var btn= document.getElementsByTagName('button');
btn.addEventListener("click", function(){console.log('You Just Clicked !!');});
<!DOCTYPE html>
<html>
<head>
    <title>Its Practice</title>
    <script type="text/javascript" src="practice.js"></script>
</head>
<body>
<h1>Hi there !!</h1>
<button>Click Me !!</button>
</body>
</html>
het99
  • 1
  • 1
  • You did not provide the HTML code, so we don't have the big picture, but I'm pretty sure you're trying to attach an event listener before the HTML code is parsed. In other words, your JS code gets executed before your HTML. Marked as duplicate – Jeremy Thille Nov 15 '20 at 13:13
  • This, OR the script gets executed after the HTML (as it should), but `getElementsByTagName` does not return ONE element (hence the name getElementS ) but a collection of elements, which you need to iterate : https://stackoverflow.com/questions/22754315/for-loop-for-htmlcollection-elements (other duplicate) – Jeremy Thille Nov 15 '20 at 13:15

0 Answers0