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.
>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();
});