最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot read properties of null (reading 'appendChild') - Stack Overflow

programmeradmin1浏览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>
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
Add a ment  | 

3 Answers 3

Reset to default 3

Code 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

发布评论

评论列表(0)

  1. 暂无评论