Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
Is there another way for refering html-dom element which is already rendered to html page without getting 'null' error?

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')
            })
    }
})
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda