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

Chintan Ray
seal-mask
.a{fill-rule:evenodd;}techdegree
Chintan Ray
Full Stack JavaScript Techdegree Student 12,309 Points

Why does my code run without any error, despite not having followed the coding instruction

Hi everyone,

I am following the video, but I code first and then look at the solution. I coded the following in my JS file:-

const myHeading = document.getElementById('myHeading'); myButton.addEventListener('click', () => { myHeading.style.color = 'tomato'; })

Link to the screenshot of the workspace ====>>> https://w.trhou.se/4wjejz3b8a

The code ran without any error, and did exactly what it was meant to do, i.e change the color of myHeading to 'tomato'.

The problem with the code is that, I have not extracted myButton from the DOM, and it still gets the element and manipulate it.

Can someone please shed some light on how that happened?

Thanks again. Cheers!!!

1 Answer

Steven Parker
Steven Parker
231,236 Points

Some browsers (obviously yours) establish a variable for every element that has an ID, using the ID as the name of the variable. While this can be handy for testing, it should not be relied on in code to be deployed for general use.