I am facing an issue where I need to update an array with values once a user clicks on an element in the DOM. It seems like the elements are getting pushed into the array inside the anonymous function, but outside the function, the array remains empty. How can I resolve this? Here is the JavaScript code snippet:
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);
}
What I essentially need is for the main array to be updated with the selected items by the users after they click on them.
Your assistance on resolving this issue would be highly appreciated.
Thank you.