Al BM
Al BM

Reputation: 3

Uncaught TypeError: Cannot read property 'style' of null in this code

I don't know why the script doesn't recognize the body.

My HTML with the script:

<html>
    <head>
        <script>
            document.body.style.overflow="hidden";
        </script>
    <body>
    <table width="2000px" height="1000px">
        <tr><td></td></tr>
        <tr><td></td></tr>
        <tr><td></td></tr>
        <tr><td></td></tr>
        <tr><td></td></tr>
        <tr><td></td></tr>
        <tr><td></td></tr>
        <tr><td></td></tr>
    </table>
</body>

The error:

Uncaught TypeError: Cannot read property 'style' of null

Upvotes: 0

Views: 118

Answers (2)

Faiz Sandhi
Faiz Sandhi

Reputation: 306

<html>
    <head>
    <body>
    <table width="2000px" height="1000px">
        <tr><td></td></tr>
        <tr><td></td></tr>
        <tr><td></td></tr>
        <tr><td></td></tr>
        <tr><td></td></tr>
        <tr><td></td></tr>
        <tr><td></td></tr>
        <tr><td></td></tr>
    </table>
    <script>
        document.body.style.overflow="hidden";
    </script>
</body>

You just have to put your script tag before body ends. right now your script tag gets executed before body tag loads.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075895

document.body is null because your code runs as soon as the script tag is encountered, and body hasn't been created yet.

Move your script to the end of the document, just prior to the closing </body> tag.


That said, there's no need for JavaScript here. You can simply add a CSS style:

body {
    overflow: hidden;
}

...or an inline style attribute on the opening body tag:

<body style="overflow: hidden">

Upvotes: 2

Related Questions