I am creating a library where you can store and remove books. I have a loop that goes through an array of books and displays them in HTML. However, when I try to remove them with the onlick function below, sometimes it works and sometimes, I'm assuming in a certain order - I get an error and the wrong item is removed.
For example, if I remove theLibrary[2] first, then I can remove the others without problems. But if I try to remove theLibrary[1] after removing theLibrary[0] succesfully, it removes theLibrary[2]. Then, if I try to remove theLibrary[1] again I get this error:
scripts.js:76 Uncaught TypeError: Cannot read property 'title' of undefined at HTMLButtonElement.toggleRemove.onclick (scripts.js:76)
Here is the code block where the problem occurs. The library is an array with book objects stored in them:
toggleRemove.onclick = function() {
// this is where problems occur
removedBook = document.getElementById(`${theLibrary[i].title}`);
console.log(removedBook);
bookRemoved = theLibrary[i];
console.log(bookRemoved);
bookRemoved.removeSelf();
removedBook.remove();
console.table(theLibrary);
}
Here is the entire DOM element creation & display block to show where these elements are coming from:
function showLib() {
for (let i = 0; i < theLibrary.length; i++) {
item = document.createElement('div');
bookTitle = document.createElement('h4');
bookAuthor = document.createElement('h4');
bookPages = document.createElement('h4');
bookRead = document.createElement('h4');
toggleRemove = document.createElement('button');
item.classList.add('item');
// add id's to items and buttons to associate with DOM
toggleRemove.setAttribute('id', `${theLibrary[i].title}`);
item.setAttribute('id', `${theLibrary[i].title}`);
removeName = document.querySelector(`#${theLibrary[i].title}`);
bookTitle.textContent = `'${theLibrary[i].title}'`
bookAuthor.textContent = `by ${theLibrary[i].author}`
bookPages.textContent = `${theLibrary[i].pages} pages`
if (theLibrary[i].read === true) {
bookRead.textContent = 'Has been read';
}
else {
bookRead.textContent = 'Has not been read';
}
toggleRemove.textContent = 'Remove Book';
item.appendChild(bookTitle);
item.appendChild(bookAuthor);
item.appendChild(bookPages);
item.appendChild(bookRead);
item.appendChild(toggleRemove);
libContainer.append(item);
toggleRemove.onclick = function() {
// this is where problems occur
removedBook = document.getElementById(`${theLibrary[i].title}`);
console.log(removedBook);
bookRemoved = theLibrary[i];
console.log(bookRemoved);
bookRemoved.removeSelf();
removedBook.remove();
console.table(theLibrary);
}
}
}
I would appreciate any tips you can give me to push me in the right direction. Thanks!