How to jquery set custom data attribute value?

Share Me
  •  
  •  
  •  
  • 4
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    4
    Shares
How to jquery set custom data attribute

Hello dev’s,
Today now in this article, i will show you how to get custom attribute value in jquery and also how to set custom attribute value in jquery. Now we will use attr() and dlso use data() for getting custom attribute value and also set custom attribute value in js. Here we know How to jquery set custom data attribute value.

Now we can easily set any data attribute value in jquery, so also we can do it same thing with by custom attribute value in jquery.

Example 1:

At first Example we will Using jquery data() function

<!DOCTYPE html>
<html>
<head>
    <title>Jquery Set custom data attribute value</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
  
<div id="example1">Click Here:</div><br>
<button class="set-attr">Set Attribute</button>

<script type="text/javascript">
 
$(".set-attr").click(function(){
    $("#example1").data('my-name', 'codingspoint');

    var name = $("#example1").data('my-name');
    alert(name);
});
  
</script>
  
</body>
</html>

Example 2 :

On second Example we will be Using jquery attr() function

<!DOCTYPE html>
<html>
<head>
    <title>Jquery Set custom data attribute value</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
  
<div id="example1">Click Here:</div><br>
<button class="set-attr">Set Attribute</button>

<script type="text/javascript">
 
$(".set-attr").click(function(){
    $("#example1").attr('my-name', 'codingspoint');

    var name = $("#example1").attr('my-name');
    alert(name);
});
  
</script>
  
</body>
</html>

Read Also : Required With All Validation in Laravel 8

Thanks for read. I hope it help you. For more you can follow us on facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →