JavaScript JavaScript and the DOM Getting a Handle on the DOM Select a Page Element By Its ID

Chintan Ray
Chintan Ray
Full Stack JavaScript Techdegree Student 12,308 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
203,727 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.