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

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
228,991 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!