Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!