Unable to add click event to button that isn’t created until the object is created

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);
});

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

  1. 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.
  2. 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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x