Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript and the DOM Getting a Handle on the DOM Select an Element by ID

Alex Francis
Alex Francis
11,625 Points

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


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

Jason Larson
Jason Larson
7,734 Points

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 Francis
Alex Francis
11,625 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.