I am creating a simple project using html,css,vanilla js for frontend and firebase 9 as backend. This is my relevant code
index.html
<body>
<div class="container"></div>
</body>
index.js
importing firebase functions here
refering those functions
// Getting data from firestore and storing it in array
onSnapshot(colRef, (snapshot) => {
let Data = []
snapshot.docs.forEach((doc) => {
Data.push({ ...doc.data(), id: doc.id })
})
// rendering data
const container = document.querySelector('.container')
let template = ''
Data.forEach(dataItem => {
template += `
<div>Some other data rendered here</div>
<span class="material-icons" id="del" data-id="${data.id}">delete</span>
`
})
container.innerHTML = template
})
//refering to btn element to get data-id value and delete that particular doc
const del = document.querySelector('.del')
del.addEventListener('click', (e) => {
const docId = e.target.getAttribute('data-id')
deleteDoc(doc(db, 'myData', docId))
.then(() => {
console.log('Deleted Successfully')
})
})
But when I am trying to get that data-id attribute it shows error "variable del is null". Am unable to refer the btn element which is rendered to html.
I tried using DOMContentLoaded too but still it shows same error. Is there any other way to refer this particular element or am I doing something wrong here ?
Thank You
UPDATE:
Hey it's working after referencing the whole container element and adding the event listener to that element and conditionally getting the doc id.
// deleting docs
container.addEventListener('click', (e) => {
if(e.target.id === 'del'){
const id = e.target.dataset.id
const docRef = doc(db, "myDB", id)
deleteDoc(docRef)
.then(() => {
console.log('Deleted Successfully')
})
}
})