getElementById works but not getElementsByTagName

Hi,

I am trying to console.log a simple message when any paragraph is clicked,

<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <p id="bob">This is a paragraph</p>
  <p>This is one too a paragraph it is!</p>
  <script>
    function changepcolor() {
      console.log("I pushed a button!");
    }
    // var Para = document.getElementById("bob"); // this works when uncommented
    var Para = document.getElementsByTagName("P"); //this doesn't work
    Para.addEventListener("click", changepcolor, false);
  </script>
</body>

</html>

In the console I get this error,

Uncaught TypeError: Para.addEventListener is not a function

Thanks

The result of getElementsByTagName is not an element. It is an array, so you’ll need to loop through each element in that array.

1 Like

E.g. something like this:

function changepcolor() {
  console.log("I pushed a button!");
}

var para = document.getElementsByTagName("p");

for(var i=0; i<para.length; i++) {
  para[i].addEventListener("click", changepcolor, false);
}
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.