Kevin Casey
Kevin Casey

Reputation: 45

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!

Upvotes: 1

Views: 218

Answers (1)

Francesco Carriero
Francesco Carriero

Reputation: 61

commentContainer.appendChild(newComment) 

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

newComment.innerText = comment;

Upvotes: 3

Related Questions