0
const btnList = [
    {
        id: 'all',
        content: 'All'
    },
    {
        id: 'br',
        content: 'Breakfast'
    },
    {
        id: 'dn',
        content: 'Dinner'
    }
];
window.addEventListener('load', () => {
    const btnz = document.getElementById('btnz');
    let newBtn = '';
    btnList.forEach(btn => {
      newBtn += `<button id="${btn.id}" class="btn-item">${btn.content}</button>`
    })
    btnz.innerHTML = newBtn;
});
const btnCollection = document.getElementsByClassName("btn-item");
console.log(btnCollection.length);

And this is HTML:

<div id="btnz"></div>

I want to create dynamic buttons, then go over newly created buttons with forEach() function. It gave me an error, so I tried log btnCollection.length and for some reason it returns me '0' instead of '3'. Why?

Enzoenzo
  • 67
  • 8
  • 1
    Move this line at the end of your `onload` function: `console.log(btnCollection.length);`. Right now, you're logging the quantity before the buttons are created – blex Apr 05 '21 at 13:09
  • 1
    See also https://stackoverflow.com/a/66480319/1169519 – Teemu Apr 05 '21 at 13:11
  • Well, I do not need to see before buttons are created, as it is just simple div as mentioned up. Instead I need to see how to check 'live' version of button collection inside btnz div – Enzoenzo Apr 05 '21 at 13:13

0 Answers0