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

Madlibs challenge TypeError

// 1. Declare variables and capture input.

const adjective = prompt("Write an adjective");
const noun = prompt("Write a noun");
const verb = prompt("Write a verb that ends with -ing");

// 2. Combine the input with other words to create a story.

const message = The ${adjective} kid talked to ${noun} when he was ${verb}.;

// 3. Display the story as a <p> inside the <main> element.

document.querySelector('p').innerHTML = message;


I can't figure out what is wrong with: document.querySelector('p').innerHTML = message;

4 Answers

If the full error is

Uncaught TypeError: Cannot set property 'innerHTML' of null 

Do you have a p element in your html?

Steven Parker
Steven Parker
231,153 Points

The whole code isn't shown here, but if the HTML portion does not have a paragraph element ("p"), that could cause this error.

If that's not it, or for future questions, always show the whole code; preferably by making a snapshot of your workspace and posting the link to it here. And if you must paste-in code, use Markdown formatting to preserve the appearance.

Thanks! I just figured it out.

Steve, You could have taken a couple of approaches here:

Add <p> element in your const message declaration, like so:

const message = `<p>The ${adjective} kid talked to ${noun} when he was ${verb}.</p>`;
document.querySelector('main').innerHTML = message;

Add <p> element in your 'display' code, like so:

const message = `The ${adjective} kid talked to ${noun} when he was ${verb}.`;
document.querySelector('main').innerHTML = `<p>${message}</p>`;

Not sure from a coding standards/conventions which approach is 'better' but Steven Parker may.

Steven Parker
Steven Parker
231,153 Points

The second example is missing accent characters around the first template string (message).
And of course, both examples require that the HTML include a "main" element, or you'd get the same error.