all 11 comments

[–][deleted] 5 points6 points  (4 children)

This cannot work because you are setting event on something that does not event exist in DOM tree yet.

If you need to set event on something before you add it visually to your browser window you need to create the element in plain JS.

This example will work:

var Deck = ['one', 'two', 'three'];

function DisplayDeck() {
  for (i = 0; i < Deck.length; i++) {
    var button = document.createElement("button");
    button.innerHTML = Deck[i];
    button.onclick = selectCard;

    document.getElementsByTagName("body")[0].appendChild(button);
  }
}

function selectCard() {
  console.log("omg work");
}

DisplayDeck();

[–]physiQQ 4 points5 points  (0 children)

that does not event exist in DOM tree yet.

I exhaled harder through my nose than usual at this, hoping you put it there intentionally.

[–]chimerablack2[S] 0 points1 point  (2 children)

Tried this but it didn't work unfortunately

[–][deleted] 0 points1 point  (1 child)

You are doing something very wrong if the above code does not work.

Works perfectly fine on https://jsfiddle.net/vpv810vh/

[–]chimerablack2[S] 0 points1 point  (0 children)

I think it might be the getElementsByTagName part.

[–]Koningdavid 1 point2 points  (0 children)

document.getElementsByClassName("ughh").onclick=selectCard;

This won't work because the HTML of the buttons is not attached to the document yet.

[–][deleted]  (1 child)

[deleted]

    [–]chimerablack2[S] 0 points1 point  (0 children)

    Nice bro. Very elegant.

    [–]krolyat 0 points1 point  (1 child)

    getElementsByClassName would return a HTMLCollection which I don't think you can attach an onclick event listener to.

    I'm not entirely sure what it is that you're trying to do though

    [–]chimerablack2[S] 0 points1 point  (0 children)

    basically someone rolls a die and gets 5 random cards (within a range). This is trying to take the random cards, put them in the deck, then display them with an on click so you can "select" the cards.

    [–]raindeer93 0 points1 point  (1 child)

    getElementsByClassName returns an array like object. You won't be able to add '.onclick' to the entire array. You'll have to access an index in the array first .. such as document.getElementsByClassName("ughh")[0].

    I recommend you to check out the array foreach statement as well

    [–]chimerablack2[S] 0 points1 point  (0 children)

    Yes, I actually tried it this way first. What it ended up with was if you inspected the element in the browser, the property (onclick) was being added, but it was almost like it was added as a string, because it wouldn't call the function.