getElementById works but not getElementsByTagName


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

<!DOCTYPE html>


  <p id="bob">This is a paragraph</p>
  <p>This is one too a paragraph it is!</p>
    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);


In the console I get this error,

Uncaught TypeError: Para.addEventListener is not a function


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);

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