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 Selecting by Id

Vic Mercier
Vic Mercier
3,276 Points

Parse error

I don't understand why there is a parseError and where?

js/app.js

index.html
<h1 id = "myNAME">VICTOR</h1>
<button id = "myBUTTON">RANDOM COLOR</button>
<script>
const name = document.getElementById("myNAME");
const myButton = document.getElementById("myBUTTON");
myButton.addEventListener("click",()=>{
  const randomColor = Math.floor(Math.random()*1000000);
  name.style.color= randomColor;
});


</script>

3 Answers

Steven Parker
Steven Parker
229,968 Points

Is this the right challenge?

Looking at the challenge linked to this question, the instructions are nothing like the code shown above. Are you working on a different challenge?

But for this challenge, you should not make any changes to the HTML code, all the work is done in app.js, and only the top 2 lines there will be modified.

But if you didn't accidentally replace the original code with something unrelated, this may be evidence of a serious bug in the question posting system.

Paul Milbank
Paul Milbank
6,445 Points

I am not sure about the answering the correct question part, but it looks like an issue with the scoping. I have noticed I can't access global variables from within a callback a couple of times. moving the name variable inside the callback seems to make the code work.

<h1 id="myNAME">VICTOR</h1>
<button id="myBUTTON">RANDOM COLOR</button>
<script>
const myButton = document.getElementById("myBUTTON");
myButton.addEventListener("click", () => {
  const name = document.getElementById("myNAME");
  const randomColor = Math.floor(Math.random()*1000000);
  name.style.color= randomColor;
});
</script>
Steven Parker
Steven Parker
229,968 Points

Global variables should be accessible in the callback.

OK, so ignoring the challenge and just looking at your code, I don't see anything in either example that would cause a parse error. Also, it should not matter where you establish name. The callback should be able to access it either way.

But neither version will successfully change the color, because the color property doesn't take a number. But something like this would work:

  const rc = () => Math.floor(Math.random()*256);
  const randomColor = `rgb(${rc()},${rc()},${rc()})`;