0
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>
  • Post your html also – Vojin Purić Oct 26 '22 at 14:59
  • 2
    Either the element with ID `generateList` doesn't exist or you're executing the javascript before the DOM is loaded. – Reyno Oct 26 '22 at 15:01
  • 1
    Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Reyno Oct 26 '22 at 15:02
  • I ran the code before DOM was loaded. Thanks for reminding me. – TheKidWhoCantCode Oct 26 '22 at 15:06

2 Answers2

2

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

  • Timing is always tricky. – QueueHammer Oct 26 '22 at 15:14
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Prateek Varshney Oct 30 '22 at 05:10
0

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.

Volodymyr Sichka
  • 531
  • 4
  • 10