How to Get Reference to Original Clicked Element When Using Event Delegation
Briefly

The code snippet outlines a process for displaying product information in a modal after a user clicks on a product div. It fetches data based on a data attribute of the clicked div and populates the modal with this data. The challenge arises when populating the clicked div with the selected data from the modal due to a lack of reference to the clicked element. The suggested solution is to define the clicked element globally when the modal is opened, allowing for easy access later.
const prods = document.querySelectorAll(".products"); prods.AddEventlistener("clicked",(e)=> fetch('some url').then(res => { if (!res.ok) { throw new Error("Cannot fetch resource!") } return res.json() }) .then(data => { const arrayObject = JSON.parse(data.data); arrayObject.forEach(prod => { const markup = `<li>${prod.Info}></li>`; document.querySelector('dialog ul').insertAdjacentHTML('beforeend', markup); }); }).catch(error => console.log(error)); });
Read at SitePoint Forums | Web Development & Design Community
[
|
]