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!
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
Brian CI
28,971 PointsTypeError: myDiv is null
I'm trying to follow the Javascript Foundations course but I am getting an error even though I think I've copied the code the exactly.
I am using firefox instead of chrome. Is it possible firefox gives errors where chrome does not? Seems unlikely.
My relevant code:
var color = "red";
var myDiv = document.getElementById('myDiv');
myDiv.style.background = "black";
myDiv.style.color = "#ffffff";
5 Answers

Brian CI
28,971 PointsD'oh. I think I see it now. I didn't remove the line above when the tutorial said to move it down lower. So one is making the error and one is working. D'oh!

dan schmidt
2,576 PointsThe problem has to be with the id. Either it is misspelled in the html or has been declared as a class instead of an id. Without seeing your code, that is as much as I can speculate.

Brian CI
28,971 PointsSee code below

Brian CI
28,971 PointsSee code below

Brian CI
28,971 Points<!DOCTYPE html>
<html lang="en">
<head>
<title> JavaScript Foundations: Variables</title>
<style>
html {
background: #FAFAFA;
font-family: sans-serif;
}
</style>
<script src="jsFoundationsVariables.js"></script>
</head>
<body>
<h1>JavaScript Foundations</h1>
<h2>Variables</h2>
<div id="myDiv">
This is a div with the id of "myDiv"
</div>
<script src="jsFoundationsVariables.js"></script>
</body>
</html>
/* JavaScript Foundations: Variables */
var color = "red";
var myDiv = document.getElementById('myDiv');
myDiv.style.background = "black";
myDiv.style.color = "#ffffff";
dan schmidt
2,576 Pointsdan schmidt
2,576 PointsYea, I see what was happening. Any javascripts that are included in the head of your document will be executed before the DOM has been populated by your browser. If want to ensure that your javascript is executed after the browser is finished rendering your page, you would assign it to the
window.onload
event: