Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

adding elements using an array via appendChild

var text = [];

function create() {
  for (var i = 0; i < 4; i += 1) {
    text[i] = document.createElement("div");
    text[i].className = "di";
    text[i].innerHTML = "hello world";
    console.log(text[i]);
    document.body.appendChild(text[i]);
  }
}
create();
.di {
  border: solid green 2px;
  margin-right: 65em;
}

I am getting a console error during rendering in Microsoft Edge Version 112.0.1722.34 (Official build) (64-bit) with the error: caught TypeError: Cannot read properties of null (reading ‘appendChild’), please explain.

Note: observe it runs without errors in the SO snippet.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The error

"TypeError: Cannot read properties of null (reading ‘appendChild’)"

occurs because the code is trying to append an element to a non-existent element or a null element.

In this case, it is possible that the JavaScript code is being executed before the DOM (Document Object Model) has finished loading, and the document.body element is not yet available. As a result, the document.body returns null, and the appendChild() method cannot be called on it.

To fix this error, you can either move the script tag to the end of the HTML file, just before the closing tag, or wrap the entire JavaScript code in a DOMContentLoaded event listener, which will ensure that the code is executed only after the DOM has finished loading.

Try:

document.addEventListener("DOMContentLoaded", function() {
 var text = [];

 function create() {
   for (var i = 0; i < 4; i += 1) {
     text[i] = document.createElement("div");
     text[i].className = "di";
     text[i].innerHTML = "hello world";
     console.log(text[i]);
     document.body.appendChild(text[i]);
   }
 }
 create();
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading