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

On my page I have several divs with a class of products and each has its own data attribute. When the user clicks one of these divs, it opens a modal, gets data about the clicked div from the database based on the data attribute of the div, and lists the data in the modal. Then when the user clicks on one of the data listed in the modal it is supposed to be displayed in the div that was clicked on the page. The problem I am having is I cannot populate the clicked div with data from the modal as I will not have reference to it when using event delegation to grab the data from the modal. The following is my code snippet/ pseudo code

 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));
});


             
1 Like

define the clicked element globally when you open the modal. Your code for opening the modal knows what was clicked, and code inside the modal can access variables in the global space.

Hi thanks for your quick reply and your suggestion works great. I was trying to get direct access to the dynamically generated elements by putting code inside of the fetch method body itself circumventing the need for event delegation and a global variable to store the reference to the clicked div but it didn’t work.