Use camelCase IDs to easily access elements in JavaScript

If you’re writing vanilla JavaScript, you can end up writing a lot of this:

<button id="menu-toggle">Menu</button>

<script>
const myButton = document.querySelector("#menu-toggle");
myButton.addEventListener("click", doSomething);
</script>

I recently found out that if you add IDs to elements in your HTML, they become available as a part of the global ‘window’ variable. For example:

   <button id="menu-toggle">Menu</button>

<script>
- const myButton = document.querySelector("#menu-toggle");
+ window["menu-toggle"].addEventListener("click", doSomething);
</script>

Every property of the ‘window’ variable is also available as a global variable (for example, window.location is the same as location). So if you use camelCase for your element IDs, they are even easier to access:

-  <button id="menu-toggle">Menu</button>
+ <button id="menuToggle">Menu</button>

<script>
- window["menu-toggle"].addEventListener("click", doSomething);
+ menuToggle.addEventListener("click", doSomething);
</script>

It's only saving one line of code, but it feels pretty handy when you're trying to put together a quick demo. I think it's good to use when:

I've put together a quick CodePen demo of a mobile nav menu using this approach.

I would avoid this approach if: