Why I getting error in browser?
TypeError: document.body is null
Code is working well in JSfiddle.
HTML
<head>
<meta charset="UTF-8">
<title></title>
<script src="jsscript.js"></script>
</head>
<body>
</body>
JS
var creElem = document.createElement("p");
creElem.innerHTML = "Hellow World";
creElem.setAttribute("id", "id_name");
document.body.appendChild(creElem);
The solution is that you need to put your JavaScript code after the closure of the HTML element or more generally before < /body > tag.
If there is no element with the given id , this function returns null . Note that the id parameter is case-sensitive, so document.getElementById("Main") will return null instead of the element <div id="main"> because "M" and "m" are different for the purposes of this method.
The TypeError: null is not an object occurs when a property is read (or set) or a method is called on a null value. An object was expected in code but was not provided. Since null is not an object in JavaScript, using a null value when an object is expected does not work.
The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.
Your document.body
is not created or not existing yet. If you want to append child to document.body
or do anything with document.body
in your javascript then put your javascript code or link of js file in the end of body tag.
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="jsscript.js"></script>
</body>
</html>
Execute the code when the DOM loads. Wrap your logic in an event listener for DOMContentLoaded
.
document.addEventListener('DOMContentLoaded', function () {
// ...
});
The reason it worked in JSFiddle is because the JS is executed on load (that's the default option in JSFiddle).
Alternatively, depending on when you need the logic to be executed, you could also use:
window.addEventListener('load', function () {
// ...
});
See: Difference between DOMContentLoaded and Load events
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With