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>
Thanks in advance!
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 aWindow
objectwindow
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-emptyid
content attribute and are in a document tree withwindow
's associatedDocument
as their root.