Sometimes, we want to fix document.body null error with JavaScript.
In this article, we’ll look at how to fix document.body null error with JavaScript.
How to fix document.body null error with JavaScript?
To fix document.body null error with JavaScript, we should reference document.body
only when the page is loaded.
For instance, we write
window.onload = () => {
const mySpan = document.createElement("span");
mySpan.innerHTML = "This is my span!";
mySpan.style.color = "red";
document.body.appendChild(mySpan);
};
to call document.body.appendChild
in the window.onload
method, which runs when the page is loaded.
If the page is loaded, that means the body element is loaded and document.body
is available.
Conclusion
To fix document.body null error with JavaScript, we should reference document.body
only when the page is loaded.