How to jquery set custom data attribute value?

11-Apr-2023

.

Admin

How to jquery set custom data attribute value?

Hii guys,

In this artical, we will learn how to get custom attribute value in jquery and how to set custom attribute value in jquery. we will use attr() and data() for getting custom attribute value and set custom attribute value in js.

We can easily set data attribute value in jquery, also you can do it same thing with custom attribute value in jquery.

Example 1:


First Example 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', 'nicesnippets');

var name = $("#example1").data('my-name');

alert(name);

});

</script>

</body>

</html>

Example 2 :

Second Example 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', 'nicesnippets');

var name = $("#example1").attr('my-name');

alert(name);

});

</script>

</body>

</html>

It will help you...

#Jquery