Dynamically listen to events and target DOM elements

I’m trying to display items from an endpoint, attach them to a DOM tree and I need to listen to events on the newly created elements and target them. But I’m only able to listen to the first element’s event and manipulate it. Is it possible to achieve this within the context of a for loop? Here’s what I have:

//Empty div
let appendSubDiv = document.querySelector(‘.subDiv’);
fetch(some.endpoint)
.then(resp=> resp.json())
.then(data=> {
let htmlString = ’ ';
data.map(function(notif){
for(const user of save_usernames){
if(…){

htmlString += <div><b><a href='#'>${notif.product_name}</a></b> <small><b>${notif.message}</b></small> <input type="hidden" value=${notif.uid} class="secret_uid" id=item_${getUidLength++}/> <button class='btx'>Mark as Read</button></div>
} }} })

window.btx = document.querySelector(‘.btx’);
let secure_uid = document.querySelector(‘.secret_uid’);
appendSubDiv.innerHTML = htmlString;

btx.addEventListener(‘click’, (event)=>{
event.preventDefault()
changeHandler(secure_uid)
})
function changeHandler(secure_uid){
let getValue = secure_uid.value;
console.log(getValue);
fetch(‘some.endpoint’,
{ method:‘PUT’,
headers:{‘Accept’:‘application/json,text/plain,/’,‘content-type’:‘application/json’},
body: JSON.stringify({‘uid’:${getValue}})})
.then(res => res.json())
.then((data)=> {console.log(Here's the data: ${data}, All's Good)})
btx.innerHTML = ‘Already Read’;
}

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.