Ad

Get The Specific Div Id From An Onclick Event (Pure JS No Jquery)

- 1 answer

When I try the code referenced in SO #1, I get the console logging a blank string:

installChoices() {
        var choices = this.game.page.options;
        for (var i = 0; i < choices.length; i++) {
            var choice = choices[i];
            var choiceDiv = document.createElement("choice" + i);
            choiceDiv.innerText = choice[0];
            choiceDiv.onclick = function() {
                console.log(this.id);
            }
            this.choicesContainer.appendChild(choiceDiv);
        }

    }

I want to bind to my class function clicked

installChoices() {
        var choices = this.game.page.options;
        for (var i = 0; i < choices.length; i++) {
            var choice = choices[i];
            var choiceDiv = document.createElement("choice" + i);
            choiceDiv.innerText = choice[0];
            choiceDiv.onclick = this.clicked;
            this.choicesContainer.appendChild(choiceDiv);
        }

    }

    clicked(e) {
        console.log(e.parentNode); //this is undefined
        console.log(e.srcElement);
    }

But that shows undefined. When I log srcElement, I get the full element

<choice0>path 1</choice0>

I want to get just the div id when I click, so I can parse that and do logic.

Ad

Answer

I'd recommend the following approach, as it is the standard:

//assign the event
choiceDiv.addEventListener('click', clicked)

//define the listener
function clicked(event) {
    console.log(event.currentTarget)
}

update:

I'm tempted to offer a fix to your code, because I don't think you're achieving what are you trying to actually do:

function installChoices() {
    var choices = this.game.page.options;
    for (var i = 0; i < choices.length; i++) {
        var choice = choices[i];
        var choiceDiv = document.createElement("div");
        choiceDiv.id = "choice" + i;
        choiceDiv.innerText = choice[0];
        choiceDiv.addEventListener("click", clicked);
        this.choicesContainer.appendChild(choiceDiv);
    }
}

function clicked(ev) {
    console.log(ev.currentTarget.id); //this will log "choice0"
}
Ad
source: stackoverflow.com
Ad