0

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

D.Kastier
  • 1,079
  • 1
  • 13
  • 27
Al BM
  • 3
  • 1

2 Answers2

2

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">
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • Yes thanks, i know that but i need to do in js, i fix this as you say it or with 'window.onload' – Al BM Sep 27 '19 at 08:40
0
<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.

Faiz Sandhi
  • 130
  • 11