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 Interactive Web Pages with JavaScript Traversing and Manipulating the DOM with JavaScript Modifying Elements

Dylan Marsh
Dylan Marsh
4,328 Points

Code Challenge: Stage 3 Traversing and Modifying DOM with JavaScript!

So I passed this code challenge already, but It doesn't quite make sense to me why we change the variable newParagraph.innerText or Html in the exercise. I understand that the newParagraph variable has a function that creates a new "P" element, but it's not the actual "P" element itself, correct? So why are we targeting the function CREATING the element instead of the element itself?Why don't we have to do something like this....?

var body = document.body;

var newParagraph = body.createElement("p");

body.p.innerText = "Your text here."

*** also, the code in the exercise is this....

var newParagraph = document.createElement("p");

why don't you have to state your creating it in the body? I thought you would have to type "= body.createElement("p") ****

2 Answers

Hugo Paz
Hugo Paz
15,622 Points

Hi Dylan,

This:

var newParagraph = document.createElement("p");

Returns the element created, so var newParagraph actually contains this:

<p></p>

If you open the console and copy paste the first code and then type newParagraph you will see the element.

If I'm understanding you correctly, I think you're asking about 2 different approaches. With regards to why you can't do something like this:

var body = document.body;
var newParagraph = body.createElement("p");

You couldn't do that mainly because the createElement() method/function is a method/function of the document object. It's not a method/function of body.

With regards to why you are CREATING the p element instead of just targeting the existing p element itself (at least I think that's what you're asking?). You could actually have just changed the text inside the existing p element (the paragraph in the page that said "Please enable JavaScript"). I haven't taken the course yet, but I would guess they just want to test you on using innerHTML. In programming, there's usually more than one way to skin a cat. So if you just wanted to change the text in the existing p element, I'm pretty certain this would work:

var pleaseEnableParagraph = document.querySelector("#please_enable");
pleaseEnableParagraph.innerHTML = "JavaScript is enabled";

Hope that makes sense.