0

I am creating elements in list tag dynamically and I want to add different event handler for all elements in list. How can I achieve this?

var menuLinks = document.getElementsByClassName('test');
    for(var j = 0; j < menuLinks.length; j++)
    {
        var menuLink = menuLinks[j];
        menuLink.onclick = function(e) {
            e.preventDefault();
            console.log(menuLink.innerHTML);
        };
    }

I added the elements in class name test but no matter which ever element I click it always gives me last element.

2 Answers2

1

Your problem is that you are creating a closure inside a loop. See JavaScript closure inside loops – simple practical example for an explanation and generic solution.

In short: JavaScript doesn't have block scope. Since there is only a single menuLink variable, every handler refers to that one variable. The variable can of course only have one value, which is the one that is set in the last iteration.


However, in your case there is a simpler solution: You can use this inside the event handler to refer to the element. You don't need to rely on the loop variable:

menuLinks[j].onclick = function(e) {
  e.preventDefault();
  console.log(this.innerHTML);
};

Learn more about this in event handlers.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

try this,

var menuLinks = document.getElementsByClassName('test');
        for(var j = 0; j < menuLinks.length; j++)
        {
            var menuLink = menuLinks[j];
            menuLink.onclick = function(e) {
                e.preventDefault();
                console.log(e.target.innerHTML);
            };
        }
Azad
  • 5,144
  • 4
  • 28
  • 56