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

139
Visualizações
How to get a class of dynamically added content via innerhtml

I am adding content to my HTML through JS by using innerHTML. But now when I try to access a class attached to that content I just get null. How would I access the class?

    fetch(url)
        .then((response) => {
            return response.json();
        }).then(data => {
            for (var i=0; i < data['data'].length; i++){
            
            var attributes = data.data[i].attributes,
                title = attributes.title,
                descr = attributes.description,
                author = attributes.author,
                available = attributes.available,
                year = attributes.year,
                id = data.data[i].id;

            var div = document.createElement("div");

            div.innerHTML = `title = ${title}, 
                             descr = ${descr},
                             author = ${author},
                             available = ${available},
                             year = ${year}
                             <button type="button" value="${id}" class="delete">delete</button>`                 

            document.querySelector('.movieList').appendChild(div)
        }
    });

const btns = document.querySelectorAll(".delete");
console.log(btns);

I have tried .getElementByClassName, but it also doesn't work :/

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It's a timing issue. You need to call querySelectorAll after you appended the elements.

Try to put const btns = document.querySelectorAll(".delete"); right after document.querySelector('.movieList').appendChild(div).

Currently, the moment when you try to find the buttons, they are not there, yet.

about 4 years ago · Juan Pablo Isaza Relatório
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