# An HTML element id is a global variable

> Did you know an HTML element with an id attribute is automatically exposed as a global JavaScript variable you can reference by name? Here is how it works.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2024-09-14 | Topics: [HTML](https://flaviocopes.com/tags/html/) | Canonical: https://flaviocopes.com/an-html-element-id-is-a-global-variable/

Little relatively unknown fact, if you have an `id` attribute on an element, you can reference it in this way:

```javascript
// html
<button id="yo">…</button>

// js
yo.onclick = ...
```

Furthermore, child elements with a name attribute can be referenced in this way:

```javascript
// html
<form id="x"> 
  <input name="em"> 
</form>

// js
x.em.onclick = ...
```

Maybe not your favorite API, but it’s a thing.
