简体   繁体   中英

How to set up a click event on HTML elements( li ) with JavaScript?

I am having some issues with running a click event. My purpose is just to track click events basically, very simple stuff. For visual changes I was going to check one of my links to change the HTML text. When I run this code at the moment I get an error:

"document.getElementsByTagName(...).addEventListener is not a function"

var links = document
      .getElementsByTagName("a")
      .addEventListener("click", myFunction);
    
    function myFunction() {
      document.querySelector(".contact-link").innerHTML = "clicked!";
    }

You need to loop through all the elements and then add the event listener

 var list = document.getElementsByTagName("a"); for(let i=0; i<list.length; i++) { list[i].addEventListener("click", myFunction); } function myFunction() { console.log("clicked"); }
 <a href="#"><span class="contact-link">ABC</span></a> <a href="#"><span class="contact-link">DEF</span></a> <a href="#"><span class="contact-link">GHI</span></a>

You can't set the event listener to all elements of the collection at once. You need to iterate over it and set the event listener for each one.

Hope it helps you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM