When I want to listen to events on dynamically created elements via JS, I need to resort to listening to the events on the body to update the element list JS is listening to. Is there not a simple elegant way to update the element database for JS to listen to when I want?
document.querySelector('body').addEventListener('click', function (event) {
if (event.target.className.toLowerCase() === 'demo-classes') {
let closeBtns = document.getElementsByClassName("demo-classes");
Array.from(demoClasses).forEach(function (demoClass) {
demoClass.addEventListener("click", function () {
myArray.splice(demoClass.id.substring(2), 1);
render(myArray);
});
});
}
});
It leads to clicking two times, once on the body and another time on the element with the demo-classes class before the splice function removes the specific item from the arrays, then the render function renders the html. All demo-classes classes are generated using createElement and classes are set using the setAttribute in the render function.
Use location.reload() to refresh your page when you want to update the database of items in getElementsByClassName function. Store the variables and dynamically elements in Session Storage/Local Storage so that it survives browser refreshes.