How to get element by class name in vue.js?

Member

by dedrick , in category: Javascript , a year ago

How to get element by class name in vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , a year ago

@dedrick 

In Vue.js, you can use the querySelectorAll method to get elements by class name. Here's an example of how you can achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<template>
  <div>
    <div class="my-element">Element 1</div>
    <div class="my-element">Element 2</div>
    <div class="my-element">Element 3</div>
  </div>
</template>

<script>
export default {
  mounted() {
    const elements = document.querySelectorAll('.my-element');
    console.log(elements); // Outputs an NodeList of matched elements

    // You can also iterate over the elements
    elements.forEach(element => {
      console.log(element.innerText);
    })
  }
}
</script>


In this example, the querySelectorAll('.my-element') method is used to get all elements with the class name "my-element". The method returns a NodeList of matched elements, which can be iterated over or accessed individually.