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

Why does this code run fine in codepen but not in a browser?

When I run this in Firefox or Chrome I get an error: Uncaught TypeError: main is null. but when I run the code in codepen it runs fine. https://codepen.io/paulzoom/pen/RwpGONj

<head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> </head>

<body> <script>

const main = document.querySelector("main"); const randomNumber = getRandomNumber(10); let guess; let attempts = 0; function getRandomNumber(upper) { return Math.floor(Math.random() * upper) + 1; } do { guess = prompt("Guess a number betwee 1 and 10."); attempts++; if (parseInt(guess) === randomNumber){ break; }

} while ( attempts < 10 ); main.innerHTML = <h1>It took you ${attempts} tries to guess ${randomNumber}.</h1>;

</script>

<main></main> </body> </html>