Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Question of var declaration

var h1 = document.querySelector('#h1');
var btn = document.querySelector(".btn");
var input1 = document.querySelector("input");
var input2 = document.querySelector("input").value;

btn.addEventListener("click",() => {
  h1.textContent = input1.value;
  h1.textContent = input2;

There are two input var call input1 and input2 and the input2 is not working, is that mean .value can not declaring together? same as .innerHTML / textContent ?

2 Answers

Steven Parker
Steven Parker
221,254 Points

The variable "input1" is just a reference to the element, so when you get "input1.value" inside the handler, you get whatever the user put into the box before clicking the button.

But "input2" is the value that was in the box when the page first loaded, so unless you pre-set the value in the HTML, it will be empty.

Also, by assigning the heading twice in a row, only the result of the second operation will be seen.

Gabbie Metheny
Gabbie Metheny
33,778 Points

It's hard to tell without seeing all of your code, but I think the problem is that in input2, you're storing the initial value of the input, which would be an empty string (""). In the case of input1, since you only stored the reference to the input, it doesn't check the value of that input until the click event is triggered, so then there's actually some content there.

Hope that makes sense, if you need more help could you post your html and css as well, or just take a snapshot of your workspace? Let me know!