Vue Get Text from Div: In Vue, the ref attribute can be used to create a reference to a specific element in your template. By setting a ref attribute on a div, you can create a reference to that element, which can be accessed in your component’s code. To get the text from the div, you can use the innerHTML property of the reference, which returns the HTML content of the element as a string. This can be useful when you need to manipulate the text or perform some action based on the content of the div.
How can you retrieve the text content of a specific div element in Vue.js?
To retrieve the text content of a specific div element in Vue.js, you can use the $refs property to access the DOM element, and then retrieve the text content using the innerHTML property. In the example code, a div element with ref="myDiv" is defined, and a method called getText is defined in the Vue instance. This method retrieves the myDiv element using this.$refs.myDiv, checks if it has any text content using innerHTML, and sets the divText data property to the text content if it exists. Finally, the text content is displayed in a paragraph element using v-if directive.
Vue Get Text from Div Example
<div id="app">
<div ref="myDiv">This is some text</div>
<button @click="getText">Get Text</button>
<p v-if="divText">{{ divText }}</p>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
divText: ''
}
},
methods: {
getText() {
const myDiv = this.$refs.myDiv
if (myDiv) {
const textContent = myDiv.innerHTML.trim()
if (textContent) {
this.divText = textContent
} else {
this.divText = ''
}
}
}
}
});
</script>


