0

Javascript Code

var orderPizzaCheck = document.getElementsByClassName("orderPizza");
orderPizzaCheck.addEventListener("click", handler);
function handler() {
  console.log("Hello from console");
}

HTML Code

<div class="order-form">
     <button type="button" class='orderPizza' id="landingButton"><a href="orderPizza.html">ORDER 
     PIZZA</a>
     </button>
  </div>

The functionality that I need:
Whenever the user clicks on the button with the className = 'orderPizza', a message on console should be displayed "Hello from console".

My Approach
In the javascript file, using document.getElementsByClassName, I'm fetching the button of className = 'orderPizza'. I add an event listener to this element by creating a function handler().

ERROR:

Uncaught TypeError: orderPizzaCheck.addEventListener is not a function

My take on:
I understand that it is a very repeated question, but I'm still unable to solve this error. I have put my script tag inside the body tag so that script is not executed prior to the html element but it still doesn't solve the issue. Please help!

Neha Chaudhary
  • 997
  • 1
  • 6
  • 19
  • 1
    If you have a single button, use `document.querySelector(".orderPizza")` instead. If you have multiple buttons… – Sebastian Simon Mar 17 '21 at 06:30
  • 1
    … use [event delegation](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of assigning multiple events — it’s more maintainable, and applies to dynamically added elements. E.g., use an [event argument](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback)’s [`target`](https://developer.mozilla.org/en-US/docs/Web/API/Event/target). See [the tag info](https://stackoverflow.com/tags/event-delegation/info) and [What is DOM Event delegation?](https://stackoverflow.com/q/1687296/4642212). – Sebastian Simon Mar 17 '21 at 06:30
  • 1
    Referring to a class should be like a collection. If your class is only one in the whole html, then add the index (`[0]`) of the first element in the collection. Like this - `document.getElementsByClassName("orderPizza")[0]`. – s.kuznetsov Mar 17 '21 at 06:32

1 Answers1

2

Only individual elements have addEventListener methods. You need to get .getElementsByClassName("orderPizza")[0].

Stuart P. Bentley
  • 8,777
  • 7
  • 48
  • 77