Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Michael Williams
PLUS
Michael Williams
Courses Plus Student 8,059 Points

Why am I getting "null" errors when using the .innerHTML property?

This is, like, suuuuuuper basic HTML and JavaScript. Yet I can't figure out why I'm getting this error. When I run the js between script tags, everything works properly. Although I don't know why the prompt makes the h1 disappear.

However, when I run the dom.html file pointing to the dom.js file, I think there's an issue, because I get an error telling me the .innerHTML is null when it's clearly not. Both files are in the same folder. Is there something else I need to do to let the html file know where the js file is when using a text editor? This is my first time outside of the workspaces.

<!DOCTYPE html>
<html>
<head>
    <!-- <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> -->
    <title>Playing with the DOM</title>
    <!-- <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" /> -->
    <script src="dom.js"></script>

</head>
<body>
    <h1 id="main-heading">Hello World!</h1>
</body>
</html>
var headingElement = document.getElementById("main-heading");
console.log(headingElement.innerHTML);
var newHeadingText = prompt("Please provide a new heading:");
headingElement.innerHTML = newHeadingText;

1 Answer

You're going to your script before the document has full loaded. Try moving <script src="dom.js"></script> to the end of the body.

Michael Williams
Michael Williams
Courses Plus Student 8,059 Points

That was it. I'm proud to say that I figured this out five milliseconds before you posted the answer, haha. So I'm learning. The only other problem I run into KRIS NIKOLAISEN is that when I run from Visual Studio Code, it makes the h1 disappear until I type something in the prompt. When I run it from the workspaces, it works like a charm.