Noobie issue or something else?

Hey guys, I really need some help here understanding why this works this way.

This is my code, it works just fine this way and when I take out the script tags and put everything on codepen correctly it works, but it will not work in an outside script I link to my HTML document. What gives? I keep getting this error. This was an intro exercise to the dom with a local Bootcamp I am in and my TA and I were at a loss.

Any explanation or help is greatly appreciated this really has me hung up.

Uncaught TypeError: can’t access property “style”, document.body is null
http://127.0.0.1:5500/tech901/w7/07-exercise-The-DOM-Me/script.js:40

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- <link rel="stylesheet" href="./style.css"> -->
    <!-- <script src="./script.js"></script> -->
</head>

<body>
    <h1>07-exercise-The-DOM-&-Me</h1>
    <p id="p2">Hello World!</p>
    <ul>
        <li>Nickname: <span id="nickname"></span>
        <li>Favorites: <span id="favorites"></span>
        <li>Hometown: <span id="hometown"></span>
    </ul>

    <script>
        document.body.style.fontFamily = "Arial, sans-serif";
    </script>
</body>


</html>

It’s because script is trying to run before the body is created, therefore document.body is null.
Put your <script></script> tag before </body>

2 Likes