0

I am trying to set event listeners for a list of HTML elements. The main code that does this is below:

let pageIds = ['functions', 'lists', 'forLoops', 'lambda', 'maps'];
let pageLinks = document.getElementsByClassName('link');

    for (var l of pageLinks) {
        console.log(l.id)
        l.addEventListener('click', () => {
            console.log(l.id + ' was clicked');
            for (var x in pageIds) {
                document.getElementById(pageIds[x] + '-div').classList.remove('show');
            }
            document.getElementById(`${l.id}-div`).classList.add('show');
        })
    }

When using the for keyword, this loop should iterate through each element individually, and thus set an event listener for each element individually.

However, when I run this code, the eventlistener function does not work as it should.

When the page loads, the console properly outputs the following:

functions
lists
forLoops
lambda
maps

The issue happens when I then go and try to click on one of the links. The event listener only ever outputs the maps id, and nothing else. I don't understand why this would be happening since the first console.log() proved that things were reading properly, but then it broke by the time it got into the eventlistener code. Each time the loop runs, l is a different HTML element, and thus should not overwrite the one before it.

Is there something in my code that I am missing?

kaitlynmm569
  • 1,605
  • 1
  • 6
  • 18

0 Answers0