VueJS Get Data Attribute Value from an Element

avatar
Published: Dec 22, 2022

Hello devs, today I'll show you how to get data attribute value from an element in VueJS application. Data attribute is quite important when we want to loop the coming response from our server side. So, let's see how we can easily implement in our VueJs application.

Note: Tested on VueJS 2.6.14.

Getting Data Attribute Value

We'll use getAttribute object to get data attribute value from an element. Let's see the below source code.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
</head>
<body>


<div id="app">
    <button @click="getAttribute($event.target)" data-id="22">Get Id</button>
</div>

<script>
    var myApp =  new Vue({
        el: '#app',
        mounted: function() {
        },
        methods :{
            getAttribute(el)
            {
                var id = el.getAttribute('data-id');
                alert(id);
            }
        }
    });

</script>


</body>
</html>

Which will produce the below result.

Clicked Element Data Attribute Value

That's it for today. I hope you've enjoyed this tutorial. If you found any difficulties o questions, catch me in comment sections. Thanks for reading. 🙂

Comments

No comments yet…