I'm trying to select to element class 'remove-book' that isn't created until after display books is ran..how do I go about selecting this remove button AFTER it's created? Here is link to the github https://github.com/Cluelesshint/library the 'displayBooks()' function is what creates that class..please help!
buttons.forEach((button) => {
if (button.className === 'new-book') {
button.addEventListener('click', function () {
const input = document.querySelector('.book-input');
openInput(input);
});
}
else if (button.className === 'add-input') {
button.addEventListener('click', addABook);
}
else if (button.className === 'remove-book') {
button.addEventListener('click', doThis);
}
console.table(buttons);
});
Try to use event delegation. The idea is simple: instead of listening events on the target element, listening events on it's ancestor elements. If an event is happening, the browser would work like the following.
- The browser checks to see if the direct parent of the element selected has an onclick event handler registered on it for the bubbling phase, and runs it if so.
- Then it moves on to the next immediate ancestor element and does the same thing, then the next one, and so on until it reaches the element.
So, when the element is clicked, the event is bubble up to its ancestor element. It doesn't care when and how the element is created.
Refactor your code with event delegation would be something like the following.
document.addEventListener('click', (event) => {
if (event.target.tagName == 'BUTTON') { // make sure the target is a button element
const button = event.target; // this is the button clicked.
const classNames = event.target.classList
if (classNames.contains('new-book')) {
const input = document.querySelector('.book-input');
openInput(input);
} else if (classNames.contains('add-input')) {
button.addEventListener('click', addABook);
} else if (classNames.contains('remove-book')) {
button.addEventListener('click', doThis);
}
}
})
note: I'm not sure why you add another event listener when a button is clicked. This is just a refactor in a perspective of event delegation