title: How to assign a javascript function by classname
body: <p>I have multiple buttons (generated by php) for a shopping cart application:</p>
  
  <pre><code>&lt;button class="addtocart" id="&lt;?php echo $code; ?&gt;"&gt; 
      &lt;span id="addtocartbutton"&gt;Add to cart&lt;/span&gt;
  &lt;/button&gt;
  </code></pre>
  
  <p>I want to update my cart using a function:</p>
  
  <pre><code>function AddtoCart() {
      alert("Added!");
  }
  </code></pre>
  
  <p>Later, I want to find the id ($code) created by the button which called it (not sure how to do that also, but maybe that's another question).  And so I tried this:</p>
  
  <pre><code>document.getElementsByClassName("addtocart").addEventListener("click", AddtoCart());
  </code></pre>
  
  <p>But it doesn't work.  It was working using an onclick, but I understand that the right way to do it by creating an EventListener.  Also, I cannot use the on() function in jQuery, because I am forced to use jQuery Version 1.6 which does not have it.</p>
  
  <p>I have looked at <a href="https://stackoverflow.com/a/25387857/989468">https://stackoverflow.com/a/25387857/989468</a> and I can't really assign it to the parent which is a p tag, because I obviously don't want the other elements in the p tag to be assigned this function.</p>