Languages
[Edit]
EN

JavaScript - why document.body is null?

9 points
Created by:
Root-ssh
178170

In this article, we would like to show you how to solve document.body is null problem in JavaScript.

Overview

Edit

Sometimes in browser JavaScript document.body can be null. It is caused because body element is not ready yet. It happens when the programmer executes source code inside head element. In this article simple solutions how to solve this problem have been described.

Example source code with issue:

Problem solutions have been presented below.

1. onload event for body tag example

Edit

2. onload event for window object example

Edit

3. DOMContentLoaded event for document object example

Edit

4. JavaScript logic execution after expected elements are loaded example

Edit

Note: the best way is to execute source source at the end of body element what has been shown in this example.

5. JavaScript logic execution after body element example

Edit

6. jQuery ready method example 1

Edit

7. jQuery ready method example 2

Edit
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join