Access DOM Elements in Vue 3 and the Composition API

In javascript, we can easily target a dom using getElementById, getElementByClassName, getElementByTagname, or querySelector. In some instances in our application we may want to target a DOM element. Let me show you how to do that in Vue the right way, or in fact the vue way.

Suppose, you want to target h1 elemenet from your component .

<template>
 <h1> hello world </h1>
</template>

where we would like to apply a css class to change the color of the text on mount. Let's find out how we can achieve that

Introducing Template refs : template ref allows to target a dom elements or instance of child component after their initial rendering.

Now in 3 steps we will be able to change our h1 color with template refs

step 1: Add ref attribute with your target element.

<template>
  <h1 ref="target" >Hello User</h1>
</template>

<style> 
.theme {
color: blue;
}
</style>

step 2: Declare a reactive state for that element with the same template ref name.It will hold the reference of the element. You can set the initial state to null since it will not hold any data.

<script setup>
import { ref } from "vue";
const target = ref(null)
</script>

Final Step : In Vue 3, the script setup runs before anything.So,you can obtain the element instance in that reactive state when the component will render.

the onMounted hook runs after the DOM has been rendered. This is only for test purposes so we can use our onMounted hook to change the color.

<script setup>
import { ref, onMounted } from 'vue'

const target = ref(null)

onMounted(() => {
// change target color
target.value.classList.add('theme')
})
</script>

And that's it. Anytime our DOM is mounted we add a class "theme" to our target element to change the text-color.

Full Code

<script setup>
import { ref, onMounted } from 'vue'

const target = ref(null)

onMounted(() => {
target.value.classList.add('theme')
})
</script>

<template>
  <h1 ref="target" >Hello User</h1>
</template>

<style> 
.theme {
color: blue;
}
</style>