jQuery Misc-data()
0 992
- This jQuery method is used to attaches data to or gets data from the selected HTML elements.
Related Topics:
jQuery Misc-get
jQuery Misc-toArray
jQuery Misc-data
Syntax:
This method has three different syntaxes to perform the different tasks.
Syntax 1
$(selector).data(name);
This signature is used to fetch the data from an HTML element.
Parameter description:
Syntax 2
$(selector).data(name,value);
This signature is used to attach data to the selected HTML element.
Parameter description:
Syntax 3
$(selector).data(object);
This signature is used to attach data to an HTML element by using the object.
Parameter description:
Example 1
In this example, we attach some data to paragraph and retrieve that data.
<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
div{
background:pink;
font-weight: 700;
padding:5px;
margin:5px;
font-size:16px;
}
p{
background:yellow;
padding:5px;
margin:5px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("#b1").click(function(){
$("p").data("mydata", "Welcome to Coding Tag");
alert("Data is attached to the paragraph.");
});
$("#b2").click(function(){
$("#res").html($("p").data("mydata"));
});
});
</script>
</head>
<body>
<h2> jQuery Misc data() method Example </h2>
<p> This is paragraph </p>
<br><br>
<div id="res">
Attched data will be show here....
</div>
<button id="b1"> Attach data </button> | <button id="b2"> Fetch data </button>
</body>
</html>
Output:
When you click the first button,
When you click the second button,
Example 2
In this example, we attach data to the paragraph by using object.
<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
div{
background:pink;
font-weight: 700;
padding:5px;
margin:5px;
font-size:16px;
}
p{
background:yellow;
padding:5px;
margin:5px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
myobj = new Object();
myobj.data1 = "Hello Everyone!";
myobj.data2 = "Welcome to Coding Tag";
$("#b1").click(function(){
$("p").data(myobj);
alert("Data is attached to the paragraph.");
});
$("#b2").click(function(){
$("#res").html($("p").data("data1")+"<br>"+$("p").data("data2"));
});
});
</script>
</head>
<body>
<h2> jQuery Misc data() method Example </h2>
<p> This is paragraph </p>
<br>
<div id="res">
Attached data will be shown here....
</div>
<br>
<button id="b1"> Attach data</button> | <button id="b2"> Fetch data </button>
</body>
</html>
Output:
When you click the first button,
When you click the second button,
Share:
Comments
Waiting for your comments