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 Create the Loop – One Solution

Why doesn't "main.innerHTML" affect the "const main"

let html;
let guess;
let input;
const main = document.querySelector('main');
const randomNumber = getRandomNumber(10);

function getRandomNumber(upper) {
  return Math.floor( Math.random() * upper ) + 1;
}

console.log(randomNumber);



// TODO: Use a loop to create a number guessing game
//  1) Ask the user to enter a number and assign that value to the `guess` variable
//  2) End the loop when the user's guess matches the random number
//  3) Display a message letting the user know they guessed the number

while (input !== randomNumber) {
  guess = prompt("I'm Thinking of a number between 1 and 10, what is it?");
  input = parseFloat(guess);
};

main.innerHTML = `<h1>You guessed the number! It was ${randomNumber}!</h1>`;  

From what I understand when you type in main.innerHTML = `<h1>You guessed the number! It was ${randomNumber}!</h1>`; shouldn't it change the const main = document.querySelector('main'); and I learned very early on in this course that a const variable cannot be changed. I was hoping someone could explain what exactly happens when the main.innerHTML = is executed?

1 Answer

Hi Daniel,

innerHtml only affects HTML code. const is Javascript (and it looks like it’s in a completely different file, so no innerHtml would not affect it).

But essentially what innerHtml does is replace all the code within the element that innerHtml is being called on.

So, let’s say your html looks like this:

index.html
<main class=“guess-num”>
    <h1>Guess the Number</h1>
    <p>Once you guess the number you win the game!</p>
</main>

main.innerHtml = “<h1>You guessed it right!</h1>” would take all of the html code between the main tag and replace it with the <h1>You guessed it right!</h1>.

Wouldn’t affect the JavaScript at all. Hope that helped.

Good question!

Thank you Brandon, it makes a lot more sense now :)