Home > database >  Cannot read properties of null (reading 'appendChild')
Cannot read properties of null (reading 'appendChild')

Time:10-27

const list = document.getElementById('generateList');
const listAdd = document.createElement('li');
listAdd.innerText = "Name"
list.appendChild(listAdd)

This code returns: Cannot read properties of null (reading 'appendChild') Why and how do I fix it?

HTML:

<ul id="generateList">

   <li>test</li>
   <li>test</li>
   <li>test</li>
   <li>test</li>
   <li>test</li>
   <li>test</li>

</ul>

CodePudding user response:

Code ran before DOM was loaded. I changed into a function and then ran it.

CodePudding user response:

This error means your list equals null and you can't call list.appendChild(...).

Log list after line const list = document.getElementById('generateList'); and check it.

  • Related