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 trialAnh Tran
2,556 PointsCannot set property 'innerHTM' of Null
When excute this code, I got the warning message in the console like this main.js:8 Uncaught TypeError: Cannot set property 'innerHTM
Here my code: const main = document.querySelector('main'); let html = '';
for (let i = 0; i <= 10; i++) {
html += <div>${i + 1}</div>
;
}
main.innerHTML = html;
Thanks everybody
2 Answers
Cameron Childres
11,820 PointsHi Anh~
Your code is looking good, but it would be easier for us to read if you use the markdown cheatsheet that's linked below the comment box like this:
```javascript
code goes here
```
This ensures we see everything you've written such as the backticks around your template literal. Here's your code with formatting:
const main = document.querySelector('main');
let html = '';
for (let i = 0; i <= 10; i++) {
html += `<div>${i + 1}</div>`;
}
main.innerHTML = html;
When I run this it gives me the expected result, showing numbers 1-11 on separate lines in the <main>
element.
However, I'll get your same error if I link the script before the <main>
element in the HTML document -- for instance, if I have the script inside the <head>
tags. This is because the script runs before the <main>
element is read, it can't see it, so it has no element to alter. Check to make sure this specific script is linked towards the end of your <body>
element.
Joseph Yhu
PHP Development Techdegree Graduate 48,637 PointsYou have to surround <div>${i + 1}</div>
with backticks.
Cameron Childres
11,820 PointsI believe the code already includes the backticks -- that's why that segment shows the way it does in the post, it's just that the forum's markdown is using them as formatting instructions.
Anh Tran
2,556 PointsI've already added backticks after someone suggests, I had changed the order of the <script> tag in the html file, put it to the end of html document and this code work fine.
Thank again everybody