1

Let's say I have multiple elements with the class game_join_a, with their respective data-tbl attributes set dynamically from a database. I want to retrieve those atrributes to further use them in my code.

The code I'm using below returns tells me that a[i] is undefined.

a = document.getElementsByClassName("game_join_a");
for(i = 0; i < a.length; i++){
    a[i].addEventListener("click", function(){
        console.log(a[i].getAttribute("data-tbl"));
    });
}
Emanuel Vintilă
  • 1,911
  • 4
  • 25
  • 35

2 Answers2

2

Try this

var a = document.getElementsByClassName("game_join_a");
for(i = 0; i < a.length; i++) {
    a[i].addEventListener("click", function (e) {
        console.log(e.currentTarget.getAttribute("data-tbl"));
    }, false);
}

Example

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
2
a = document.getElementsByClassName("game_join_a");
for(i = 0; i < a.length; i++){
    a[i].addEventListener("click", function(){
        console.log(this.getAttribute("data-tbl"));
    });
}

this refers to the element that the click event is binded to. If you're dynamically adding the elements rather than just the data- attributes, you could also try this:

var a = document.getElementById('game_join_container'); // just something that contains all the elements that will be dynamically added

a.addEventListener('click', function (event) {
    // check to see if original element clicked is a "game_join_a" element first
    if(event.target.classList.contains('game_join_a')) {
        console.log(event.target.getAttribute('data-tbl'));
    }
});
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153