Vue.Js get element by id


We use $refs to access the DOM elements in vuejs. We can use $refs property to access the element by id. You can add the $refs attribute to the any element to vue instance. Here in this article, we are going to explain how to use the $refs property to access the elements.


Get Element By Id Or Refs Example

You can access any element using $refs in vue.js. Here is simple example.

Example:

<!DOCTYPE html>
<html>
<head>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
</head>
<body>
<div id="app">
	<div id="myId" ref="myId">{{ message }}</div>
	<button @click="myFunction()">Click Me</button>
</div>
<script>
 new Vue({
el: '#app',
  
  data: { 
	  message:"Welcome"
  },
  
   methods:{
    myFunction: function () {		
		this.$refs.myId.innerText = 'Hello World';
    }
	}

});
</script>        
</body>
</html>

Try it »

On the same way you can access any element using ref same as id.

Output of above example-

Vue.js get element by id example

Advertisements

Add Comment

📖 Read More