Search code examples
vue.jsvuejs3vue-composition-apivue-sfc

Vue 3 - How is this possible? Accessing to DOM element without ref() or document.querySelector()


I've noticed that I can access a DOM element without creating any variable or ref.

I haven't found anything in the documentation about this. It's like you can access all elements with IDs without creating pre-references. Is this normal or is it a bug?

<script setup>
import { onMounted } from "vue";

onMounted(() => {
  // How is this possible?
  customId.innerText = "Hello" 
});
</script>

<template>
  <div id="customId">Hi</div>
</template>

https://sfc.vuejs.org/#eNo9kL1uwzAMhF+F4JQAjbS7totu7tCtI5fEZhoF1g9EOSlg+N1Lx20WgeRRh+8443tK5jYxVlhLn10qIFym1FJwPsVcYIYYPuMUCg+wwDlHD4T6g/CVAoWnuNvtoWlhpgBgLXTxDk6gXPRJUcSdRn5btX6SEv3HYFwInL/4p0Cjjh2PYyQECstejWu70SiHNoV9Go+FtQOoB3cDNzSE/1aEbedqq3NdqO1zG19wC3Hwx2SuEoPGfADSnyCE1Ya8zh6pKi0upSSprJVzvx7nKibmb6uVyZrVeTYs/nDK8S6c1ZhwtViUHZdfmwp0rw==

Thanks in advance!


Solution

  • This is not specific to Vue, but HTML/JavaScript in general.

    Elements with an id attribute are available globally in a variable (actually a property in the window object) whose name is the element's id.

    See Named access on the Window object:

    The Window object supports named properties. The supported property names of a Window object window at any moment consist of the following, in tree order according to the element that contributed them, ignoring later duplicates:

    (...)

    • the value of the id content attribute for all HTML elements that have a non-empty id content attribute and are in a document tree with window's associated Document as their root.