Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
How to target elements inside <script setup> of Vue 3 component?

How can I target the element with test class inside this vue component:

<template>
  <div id="test" class="test">

  </div>
</template>


<script setup>

console.log(document.querySelector('.test'))
</script>

This component is imported into another component. The console outputs null.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

the component is not rendered before that script is run

You want to wait until it is mounted

<template>
  <div id="test" class="test">

  </div>
</template>


<script setup>

import { onMounted } from 'vue'; 
onMounted(() => { 
    console.log(document.querySelector('.test')) 
});
</script>

In general, there's hardly ever any need to use DOM methods like that in vue though - I won't say never, because I know as soon as I say that, someone will come up with a valid reason to

I never have though

about 4 years ago · Juan Pablo Isaza Report

0

The best practice is to use ref instead of DOM manipulations methods, and also use onMounted hook to check the element as mentioned in the following example:

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

const input =ref()
onMounted(()=>{

  input.value.focus()
})
</script>

<template>

  <input  ref="input">
</template>
about 4 years ago · Juan Pablo Isaza Report

0

you can use onMounted for target the element inside vue component:

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

onMounted(() => {
  console.log(document.querySelector('.test'));
})
</script>

but I recommend use ref instead of DOM manipulations method:

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

const el = ref()

onMounted(() => {
  el.value // <div>
})
</script>

<template>
  <div ref="el"></div>
</template>

docs: https://vuejs.org/api/composition-api-lifecycle.html#onmounted

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!