Scott Whittaker

Software engineer

Day job React | side projects Svelte

DOM element id as global property

I was recently looking at an older piece of JavaScript code and was confused about how a DOM element was being populated with text. For example, if we have the following markup and JavaScript we see the word Hello in the DOM.

<p id="test"></p>
test.textContent = 'Hello';

I was looking in code for document.getElementById('test') to see where we get a reference to the element but none existed, yet the value exists in the DOM.

It turns out that ids are created as properties of the global object by default. You can see by typing window.test in the browser console that test has been added as a property on the window object.

> window.test
    <p id="test">Hello</p>

This is a long outdated practice but it caught me out for few minutes. There is a good explanation here describing the history behind this.