Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

212
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda