javascriptdomappendchild

Cannot read properties of null (reading 'appendChild')


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>


Solution

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