Search code examples
javascriptjsonajax

Using addEventListener and getElementsByClassName to pass an element id


I'm defining a list of items from a JSON file and displaying that list on a web page. The intention is for users to click on any item in that list to display more information on that item (information that is held in the same JSON file).

All items of that list are members of the same class, and each has a unique id defined from the JSON file. The HTML looks something like this:

<ul>
   <li class="menu" id="bob">Robert Smith</li>
   <li class="menu" id="jane">Jane Doe</li>
   <li class="menu" id="sue">Susan Carter</li>
</ul>

I was planning to use something along the lines of

var userSelection = document.getElementsByClassName('menu');

in concert with

userSelection.addEventListener('click', myFunctionToPrintDetails());

but I am not sure how to pass the id from the event listener to the print function in order to determine which details to print.

I have a lot of experience with HTML/CSS but very little with JSON/AJAX, so possible I'm going about this completely bass-ackwards. If there is a more appropriate way to get this done I'm open to the feedback.

I tried both answers but neither worked. When I log userSelection.length to the console I get 0; when I log userSelection I get:

HTMLCollection(0)
> sue: li#sue.menu
length: 3
> jane: li#jane.menu
> bob: li#bob.menu
> 0: li#bob.menu
> 1: li#jane.menu
> 2: li#sue.menu

Solution

  • codepen demo

    var userSelection = document.getElementsByClassName('menu');
    
    for(var i = 0; i < userSelection.length; i++) {
      (function(index) {
        userSelection[index].addEventListener("click", function() {
           console.log("Clicked index: " + index);
         })
      })(i);
    }
    

    As pointed out by @torazaburo in the comments, you can use the following if the browsers you want to support are complying with ECMAScript 6 (ES6), the newest version of JavaScript.

    var userSelection = document.getElementsByClassName('menu');
    
    for(let i = 0; i < userSelection.length; i++) {
      userSelection[i].addEventListener("click", function() {
        console.log("Clicked index: " + i);
      })
    }