Collecting Data From a Pressed DOM created Button

Viewed 43

So I'm trying to create a sort of deck creator in JS, I have the prototype, but I want to make it a bit more modular. So I made a else loop to create DOM buttons. The problem I'm having is I can't seem to figure out how to get the id/any number from the SPECIFIC button I pressed.

var cardName = ["Card 1", "Card 2", "Card 3", "Card 4", "Card 5", "Card 6"]
var Card;
var isInDeck = ["false", "false", "false", "false", "false"];
var Deck = [];
for (var i = 0; i < cardName.length; i++) {
  var button = document.createElement("button");
  button.innerHTML = cardName[i];
  button.classList = "Button";
  button.setAttribute('id', cardName[i]);
  document.getElementById("buttonPlace").appendChild(button);
}

EDIT, I have already tried adding

button.onClick = function () {Card = i;} 

after it in the for loop, and it didn't work,

1 Answers

You can add an eventlistener to the button. With that you can get all the data your button currently holds

for (var i = 0; i < cardName.length; i++) {
  var button = document.createElement("button");

  ... // your button setup

  button.addEventListener('click', function() {
      console.log(this); // this is your button element
      console.log(this.id); // this is the ID you assigned with "setAttribute"
  });

  document.getElementById("buttonPlace").appendChild(button);
}

This way you can access any data you assigned to the button beforehand. In the callback function for click you can then do further stuff with your data.

If you don't want to have an anonymous function inside your loop, you can seperate it like following:

function myFunction() {
    console.log(this); // this is your button element
    console.log(this.id); // this is the ID you assigned with "setAttribute"
}

for (var i = 0; i < cardName.length; i++) {
  var button = document.createElement("button");

  ... // your button setup

  button.addEventListener('click', myFunction);

  document.getElementById("buttonPlace").appendChild(button);
}

Look on mozilla.org for more on eventlistener

Related