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 Getting a Handle on the DOM Select an Element by ID

Alex Hort-Francis
Alex Hort-Francis
17,074 Points

Variable 'headline' not defined, but function still runs! Mysterious..

Hello,

With this code:

const button = document.getElementById('btn-main');

button.addEventListener('click', () => {
  headline.style.border = 'solid 2px red'; 
});

... the headline does indeed get a red border when the 'Update Heading' button is pressed.

However, the variable 'headline' in the Javascript has not been defined!

Typing 'headline' in the console returns the correct h1 element: <h1 id="headline" style="border: 2px solid red;">My Day</h1>

I can't figure this one out! Does anyone else know?

Is it something to do with browser cache keeping the 'headline' variable maybe?

1 Answer

This works because you are modifying an element that has an id of "headline". It wouldn't work on a class or element, or if the name of the id doesn't conform to standard variable naming (like "btn-main"). Ids are created by default as properties of the global object (in global context). (Please don't ask me where this is documented, as I don't know. I found it googling around for the answer to your question.) Basically, ids act very similar to a global variable. You should avoid this use of them, though, as you could run into issues that are difficult to troubleshoot (like if you had a global variable named "headline", as it would shadow the "headline" property).

Alex Hort-Francis
Alex Hort-Francis
17,074 Points

Woah, that's crazy! So in effect when the browser renders the HTML into a DOM, it assigns elements with an ID to variables..

I suppose this has something to do with the fact you can navigate a webpage using the ID values in the url..

I just checked and yeah you can reassign the variable 'headline'; I made it into a string ('hello!'). You can even redefine it as a const.

I wonder if the browser is creating this ID variable as a var? Rather than let or const.

Thanks for your answer, that was very instructive :)

I don't imagine there is much one can do specifically with these ID variables (properties of the global object, like you say), but it's interesting to know that they exist.