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 JavaScript and the DOM (Retiring) Getting a Handle on the DOM Select a Page Element By Its ID

Can't use the "value" property value on the variable definition?

I've always wondered this: why can't I just add

.value

to the element when I define the variable? Like this:

const input = document.getElementById('Input').value;

If I do that, then the function doesn't work.

1 Answer

Steven Parker
Steven Parker
231,008 Points

You're right, that should work.

Are you sure that the ID of the element you want the value of is actually "Input"? The one in the video is "myTextInput".

Also, are you doing that inside the handler code? If you do it where myTextInput was being assigned in the video, it will always be an empty string.

Are you sure that the ID of the element you want the value of is actually "Input"? The one in the video is "myTextInput".

Yup, I used Input instead just to make it shorter.

Also, are you doing that inside the handler code? If you do it where myTextInput was being assigned in the video, it will always be an empty string.

Right, that's what I meant. If I do blahblah.value within the function, it works. What I'm trying to understand is why the following won't work:

const input = document.getElementById('Input').value;

btn.addEventListener('click', () => {
  heading.style.color = input;
});
Steven Parker
Steven Parker
231,008 Points

It "works" technically. But as I said before, if you do it there, input will always be an empty string because the value is being sampled when the page is first loaded.

But when you do it in the handler, the value is sampled after the user has had a chance to put something in the box and then click on the button.

Ahhh ok I get it now. Thank you!