1
var elems = document.getElementsByClassName('delButton');
    for(i=0; i<elems.length; i++){
        var attr = elems[i].getAttribute('data-rowid');
        elems[i].addEventListener('click',function(){
            console.log(attr);
        });
    }

When I click on any of the buttons, only the value of data-rowid attribute of the last element (delButton) is being output on the console. How do I print the data-rowid value associated with each of the buttons?

Tanmay
  • 3,009
  • 9
  • 53
  • 83
  • 3
    The linked question's answers explain why you're getting what you're getting. But the solution in this case is quite simple: Get rid of your current `getAttribute` line, and instead use `console.log(this.getAttribute("data-rowid"));` *inside* the event handler. – T.J. Crowder Feb 15 '17 at 08:22
  • Also note that your code is falling prey to [The Horror of Implicit Globals](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html) *(that's a post on my anemic little blog)*. You need to declare `i`. – T.J. Crowder Feb 15 '17 at 08:28

1 Answers1

4

Try this

var elems = document.getElementsByClassName('delButton');
    for(i=0; i<elems.length; i++){
        elems[i].addEventListener('click',function(){
            console.log(this.getAttribute('data-rowid'));
        });
    }

You are not getting the expected result due to the fact the scope of the closure is such that only the last attr is evaluated.

While in the proposed solution you are extracted the attr from the element receiving the event

pinturic
  • 2,253
  • 1
  • 17
  • 34