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 Object-Oriented JavaScript (2015) Introduction to Methods Different Kinds of Objects

David Diehr
David Diehr
16,457 Points

innerHTML and getElementById are weird, aren't they?

While I understand the basics of how innerHTML and getElementById methods work, something about them strikes me as very odd. Usually, when you set a variable, that variable is now totally independent from whatever you used to set it's value. Changing that variable after the fact, won't change the value of anything that was used to set it. If you use variable a to set variable b, and then later change variable b, variable a remains untouched.

However, when you set a variable by using the getElementById method and then change the value of that variable with the innerHTML method, you're not just changing the value of that variable, you're changing the HTML element that was used to set it. This seems to run counter to the vary nature of variables. And while I understand the usefulness of this kind of behavior I'm left wondering how this can be technically valid?

Anybody willing to share their expertise on the subject? Is there anywhere else in JS other than dealing with HTML documents where this kind of variable behavior exists?

1 Answer

Joe Brown
Joe Brown
21,465 Points

I think your missing the connection between the element you get by Id and innerHtml. innerHtml is just a property of an html element(which is a sort of object itself) you select. Like any other language where you create classes/objects and create properties that describe their "state" then. You said you are changing the element you selected when you change the innerHtml property but that's not correct, your just changing the value of one of its properies, innerHtml. Do a console log of the element you select first, change the innerHtml, and then log just the element again, and you should see you are still referencing the same element.