I'm trying to update the array with values once the user clicks on an element in the DOM. The elements seem to be pushed into the array inside the anonymous function but outside the function the array is still empty. How can I fix that? Here is the javascript code:
function getSelection() {
var selections = [];
var container = document.getElementById("main-container");
var choices = document.querySelectorAll('li');
choicesLength = choices.length;
for(var i = 0; i < choicesLength; i++) {
choices[i].addEventListener("click", function(){
var position = this.getAttribute("value");
selections.push(position);
// logs array and updates with each click
console.log(selections);
});
}
// logs empty array
console.log(selections);
}
Basically, after the items are clicked, the main array needs to be updated with what they clicked.
Any help would be appreciated.
Thanks