In my project I need to create button dynamically. I wrap it to div and this div is appeded to container called tableDoc. My problem is that in this case onclick function doesn’t work.
If my button is appended straight to tableDoc with not being wrapped to div before it works fine.
Could you tell me why onclick function doesn’t work if wrapped to div?
Example with button wrapped to div before being added to tableDoc:
Elements.map(item=>{
const div=document.createElement('div');
///////adding button////////////////
var deleteButton = document.createElement("button");
deleteButton.setAttribute('type','button');
deleteButton.setAttribute('class',"btn-close");
deleteButton.setAttribute('aria-label','Close');
deleteButton.setAttribute('id',item.pk);
deleteButton.onclick = function() {
alert("blabla");
};
//////////////////////////////////////////////////////
div.innerHTML+=item.fields.car+' '+item.fields.model
div.appendChild(deleteButton);
tableDoc.appendChild(div);
div.innerHTML+='<br>'
})
secondary example with button added straight to tableDoc:
Elements.map(item=>{
const div=document.createElement('div');
///////adding button////////////////
var deleteButton = document.createElement("button");
deleteButton.setAttribute('type','button');
deleteButton.setAttribute('class',"btn-close");
deleteButton.setAttribute('aria-label','Close');
deleteButton.setAttribute('id',item.pk);
deleteButton.onclick = function() {
alert("blabla");
};
//////////////////////////////////////////////////////
div.innerHTML+=item.fields.car+' '+item.fields.model
tableDoc.appendChild(deleteButton);
tableDoc.appendChild(div);
div.innerHTML+='<br>'
})