TheKidWhoCantCode
TheKidWhoCantCode

Reputation: 47

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>

Upvotes: 0

Views: 7953

Answers (3)

Dimitri Rozomashvili
Dimitri Rozomashvili

Reputation: 21

For me, the problem was the same as @TheKidWhoCantCode said

I had buttons:

let div = document.querySelector(".div-buttons");

and I solved it just by saving my HTML document, as I think it returned null because in this case there wasn't a div-buttons class until I saved it

Upvotes: 0

TheKidWhoCantCode
TheKidWhoCantCode

Reputation: 47

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

Upvotes: 3

Volodymyr Sichka
Volodymyr Sichka

Reputation: 561

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.

Upvotes: 0

Related Questions