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>
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>
Share
Improve this question
edited Oct 26, 2022 at 15:02
TheKidWhoCantCode
asked Oct 26, 2022 at 14:58
TheKidWhoCantCodeTheKidWhoCantCode
471 silver badge9 bronze badges
4
- Post your html also – Vojin Purić Commented Oct 26, 2022 at 14:59
-
2
Either the element with ID
generateList
doesn't exist or you're executing the javascript before the DOM is loaded. – StackByMe Commented Oct 26, 2022 at 15:01 - 1 Does this answer your question? Why does jQuery or a DOM method such as getElementById not find the element? – StackByMe Commented Oct 26, 2022 at 15:02
- I ran the code before DOM was loaded. Thanks for reminding me. – TheKidWhoCantCode Commented Oct 26, 2022 at 15:06
3 Answers
Reset to default 3Code ran before DOM was loaded. I changed into a function and then ran it.
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.
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