Skip to main content

How do you access the DOM through ref?

To access the DOM through ref in Vue, you use a template ref - a ref that is bound to a real DOM element. Access to the DOM becomes available only after the component is mounted.


1. Using ref in the Composition API

Step 1: create a ref variable

js
const inputEl = ref(null)

Step 2: bind it in the template

html
<input ref="inputEl" />

Step 3: access it in onMounted

js
onMounted(() => { inputEl.value.focus() // inputEl.value is the real DOM element })

A full example

vue
<script setup> import { ref, onMounted } from 'vue' const inputEl = ref(null) onMounted(() => { console.log(inputEl.value) // <input ...> inputEl.value.focus() }) </script> <template> <input ref="inputEl" /> </template>

What can you do with the DOM element?

js
inputEl.value.focus() inputEl.value.blur() inputEl.value.style.color = 'red' inputEl.value.classList.add('active') inputEl.value.getBoundingClientRect()

Any methods of regular DOM elements are available.


Important rules

1. ref is available only after onMounted

Before mounting:

js
console.log(inputEl.value) // null

2. ref returns the DOM element itself

Not a reactive object, it is a direct reference to the element.

3. If the element is hidden through v-if

ref will be null until the element appears.

4. With v-for, ref → an array of refs

For example:

html
<div v-for="item in items" :ref="elRefs">...</div>

Example with a "Scroll to element" button

vue
<script setup> import { ref, onMounted } from 'vue' const box = ref(null) function scrollToBox() { box.value.scrollIntoView({ behavior: 'smooth' }) } </script> <template> <button @click="scrollToBox">Scroll</button> <div ref="box" style="margin-top:1000px">Target</div> </template>

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.