Home > Net >  Why is appendChild not appending from array but instead replacing?
Why is appendChild not appending from array but instead replacing?

Time:10-27

So my problem is that my code is replacing instead of appending.

<div>
            <button  id="toast_btn">Click me please</button>
            <div id="container"></div>
</div>




const toastBtn = document.getElementById('toast_btn');
const container = document.getElementById('container');
const notif = document.createElement('div');
notif.classList.add('toast');

 const myArray = [
    {
        notification: "1"
    } , {
        notification: "2"
    }, {
        notification: "3"
    }, {
        notification: "4"
    }, {
        notification: "5"
    }, {
        notification: "6"
    }, {
        notification: "7"
    }, {
        notification: "8"
    }
];

toastBtn.addEventListener('click', () => {
    createNotification();
})

function createNotification() {

    let random = Math.floor(Math.random() * myArray.length);

    notif.innerText = myArray[random].notification;

    container.appendChild(notif);

    setTimeout(() => {
        notif.remove();
      }, 3000);
};

So what I'm trying to do is, on click, show a notification and let the notifications linger for a bit in a list, showing all the notifications I've made appear. It worked fine when I had just one notification text. But after adding the array from which it randomly chooses one, it replaces the notification with a new one instead of adding it to the list of notifications showing.

English is not my first language, so sorry if my explanation was unclear.

CodePudding user response:

appendChild will remove an existing node from its parent, and then append it. You are therefore attempting to remove a node from its parent, only to then append it back where it already was.

To fix this, do notif = document.createElement('div'); (immediately before the notif.innerText = line) to create a new node prior to appending it.

  • Related