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

Tony Shangkuan
Tony Shangkuan
7,200 Points

Is is possible to concatenating another String to InnerHTML?

Here is the code I wrote:

var message = document.querySelector("body"); message.innerHTML=<h1>1st string content</h1>; message += "2nd string content";

console.log(message);

Intuitively, I thought this would work, but I ended up getting this [object HTMLBodyElement] Is there something wrong with my code?

1 Answer

Steven Parker
Steven Parker
231,248 Points

Instead of appending to message.innerHTML, this code is attempting to add the string directly to message (the body element itself).

Since the message variable doesn't currently contain a string, the system first reassigns it using a string that describes the body element and then concatenates the new string onto that.

Tony Shangkuan
Tony Shangkuan
7,200 Points

Ok, so you mean we can not concatenates strings this way even though message.innerHTML may seem to be string but in fact it is not?

Steven Parker
Steven Parker
231,248 Points

This code was not appending to message.innerHTML, which is a string. What this code was appending to is message itself, which was originally assigned to the element object.

message += "2nd string content";             // original code
message.innerHTML += "2nd string content";   // corrected code
Tony Shangkuan
Tony Shangkuan
7,200 Points

Thanks so much for the clarification ! Now I get it!