lundi 8 juillet 2019

How to fix "The node to be removed is not a child of this node." error in JavaScript?

so I'm making a notification and I want it to close itself after 10 sec but also I want to close this notification by my myself by using an icon.

But first issue is that I can close only first notification. (don't know why)

And the second one is that when I close that notification after 10 sec I got this on console: " Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node. "

class Notification {
  addNotification(settings) {
    let notificationContent = `
      <div class="notification__icon">
        <i class="${icon}" style="color: ${textColor}"></i>
      </div>
      <div class="notification__exit-icon">
        <i class="fas fa-times-circle"></i>
      </div>
      <div class="notification__content">
        <h1 class="notification-title" style="color: ${textColor}">${
      this.title
    }</h1>
        <p class="notification-message">${this.message}</p>
      </div>`;

    let newDiv = document.createElement("div");
    newDiv.classList.add("notification-area");

    let notification = document.createElement("div");
    notification.classList.add("notification");
    notification.innerHTML = notificationContent;

    const area = document.querySelector(".notification-area");

    if (!area) {
      newDiv.appendChild(notification);
      document.body.appendChild(newDiv);
      setTimeout(function() {
        newDiv.removeChild(notification);
      }, 10000);
    } else {
      area.appendChild(notification);
      setTimeout(function() {
        area.removeChild(notification);
      }, 10000);
    }

    let exitIcon = document.querySelector(".notification__exit-icon");

    exitIcon.addEventListener("click", event => {
      event.target.parentElement.parentElement.remove();
    });
  }
}

Aucun commentaire:

Enregistrer un commentaire