0

How can I delete the parent element of a child using an event listener.

I have an html form that when submitted, runs the makeNewBook function and pushes an object containing the form information to an array called myLibrary. It then creates a container div that displays the info from that form, which is placed in a predefined div called shelf(bookshelf). That container also has a delete button in it.

The delete button has an event listener that removes the object from the array, but how can I also remove the container from the page using that last event listener? Thanks

Javasctipt:

function makeNewBook() {
    let x = new Book(bookInput.value, authorInput.value, pagesInput.value, readInput.value)   //create a new book using the input vals
    myLibrary.push(x)                                                                         //push the new book object to the books array;
    console.table(myLibrary)


    let container = document.createElement('div')    //create a container for all the info
    container.setAttribute('class', 'container')

    let titlePara = document.createElement('p')
    titlePara.textContent += 'Title: ' + x.title;
    let authorPara = document.createElement('p')
    authorPara.textContent += 'Author: ' + x.author;
    let pagesPara = document.createElement('p')
    pagesPara.textContent += 'Pages: ' + x.pages;
    let readPara = document.createElement('p')
    readPara.textContent += 'Read: ' + x.read


    // delete button
    let deleteBtn = document.createElement('input');
    deleteBtn.setAttribute('class','delete')
    deleteBtn.type = 'submit';
    deleteBtn.value = 'Delete'



    // append everyhting to the container div to be put on the shelf
    container.appendChild(titlePara)
    container.appendChild(authorPara)
    container.appendChild(pagesPara)
    container.appendChild(readPara)
    container.appendChild(deleteBtn)
    container.setAttribute('class', `container ${x.title}`)
    shelf.append(container)




    deleteBtn.addEventListener('click',()=>{
        let index= myLibrary.indexOf(x); 
        myLibrary.splice(index,1);       //delete that object from the myLibrary array

        document.body.remove(deleteBtn.parentElement)    //This does not work
    })

}

1 Answer 1

1

You have to call remove on the node itself

deleteBtn.parentElement.remove();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.