How to get element by id in Vue JS?

In this article will explain how to get element by id in Vue js. This example will help you to get element by id using refs in vue js application.

If you are a using simple jQuery and you require to change text or replace text of specific element then you can do it easily follow below example.

In Vue js you can’t do it very simple, but you can do it using refs variable. So, just below example and learn about that.

1. How to get element by id in Vue.js using refs system
Example
 <div id="app">
     <div id="mId" ref="mId"> {{ message }}
     <button @click="clickFunction()">Click me</button>
    </div>

    <script type="text/javascript">
        new Vue({
            el: '#app',
            data: {
                message: "Welcome here"
            },
            methods: {
                clickFunction: function () {
                    this.$refs.mId.innerText = "Hello users";
                }
            }
            
        });
    </script>

Explanation:

  • Add ref=”mId” to the element you want to access.
  • Use this.$refs.mId to access the element.
Example

In below example shows vue js component code for get element by id in vue js.

<template>
<div>
<button id="mButton" @click="clickButton()">Click me</button>
</div>
</template>

<script>
export default {
    methods: {
        clickButton() {
           this.$refs.mButton.style.backgroundColor = 'blue';
        },
    },
};

</script>

Explanation:

  • Add ref=”mButton” to the element you want to access.
  • Use this.$refs.mButton to access the element.

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *