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.

3
  • You simply iterate over the elements and add the handlers? Please elaborate. Commented Nov 21, 2015 at 16:45
  • I created elements dynamically. The problem is that when I add event handler, it only calls the handler of the last element in the list even if I click on the first element. Commented Nov 21, 2015 at 16:54
  • Then you are probably doing something wrong. Please post your code. See minimal reproducible example. Commented Nov 21, 2015 at 16:57

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
            };
        }

1 Comment

What makes you think the OP uses jQuery?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.