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

213
Visualizações
How to properly add a button to a div in javaScript

Im making a baisc CRUD app and am having trouble with my delete and edit buttons. I can add the delete button to the main container but cannot add it to the comment within the container.

let submitBtn = document.getElementById("submitBtn");
let commentContainer = document.getElementById("commentsContainer")

//Delete Button
let deleteBtn = document.createElement("button");
deleteBtn.classList.add("deleteBtn")
deleteBtn.innerText =  "Delete"




submitBtn.addEventListener("click" , function postComment() {
    let comment = document.getElementById("comment").value
    let newComment = document.createElement("div")
        if(comment == ""){
            //No comment typed alert
            alert("Please type a comment!")
        } else {
          //Inserting comment into container
           commentContainer.appendChild(newComment)
           newComment.classList.add("comment")
            

           //Line in question
           newComment.appendChild(deleteBtn)

        //commentContainer.appendChild(deleteBtn) works just fine

           //Setting Comment text
           newComment.innerText = comment;
        }
    deleteBtn.addEventListener("click" ,() =>{
        //Deleteing all comment attributes
        newComment.remove()
        deleteBtn.remove()
    })
    })

The button works however I cannot for the life of me figure out why when I try to append it to the div that contains the comment JS doesnt create the button but when I append it to the comments parent div it works fine.

Any and all help is greatly appreciated. Thanks!

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

commentContainer.appendChild(newComment) 

Must be the last instruction, and should be moved at the end of the else under this line:

newComment.innerText = comment;
about 4 years ago · Santiago Gelvez 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