Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: document.body is null

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);
like image 281
Getup4 Avatar asked Jan 08 '15 04:01

Getup4


People also ask

How do I fix uncaught TypeError document getElementById is null?

The solution is that you need to put your JavaScript code after the closure of the HTML element or more generally before < /body > tag.

Why is my document getElementById returning NULL?

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.

Is null JavaScript error?

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.

What is get element by ID in JavaScript?

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.


2 Answers

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>
like image 78
Sharifullah Sharif Avatar answered Oct 16 '22 10:10

Sharifullah Sharif


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

like image 29
Josh Crozier Avatar answered Oct 16 '22 09:10

Josh Crozier