Reputation: 9
.data()-Attaches
data to, or gets data from, selected elements. A method in jQuery
Question:
1) What the purpose of this method ?
2) When I run it, I see NO data-* attribute created. So what is the difference between data-*
attribute and data created by data()
method in jQuery?
<!--code from w3school -->
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("div").data("greeting", "Hello World");
});
$("#btn2").click(function(){
alert($("div").data("greeting"));
});
});
</script>
</head>
<body>
<button id="btn1">Attach data to div element</button><br>
<button id="btn2">Get data attached to div element</button>
<div></div>
</body>
</html>
Upvotes: 1
Views: 321
Reputation: 510
The .data() method allow you to attach data of any type of DOM elements in a way that is safe from circular references and therefore from memory leaks.
We can set several distinct values for a single element and retrieve them later: (Documentation example)
$( "body" ).data( "foo", 52 );
$( "body" ).data( "bar", { isManual: true } );
$( "body" ).data( { baz: [ 1, 2, 3 ] } );
$( "body" ).data( "foo" ); // 52
$( "body" ).data(); // { foo: 52, bar: { isManual: true }, baz: [ 1, 2, 3 ] }
"Using the data() method to update data does not affect attributes in the DOM. To set a data-* attribute value, use attr.
Prior to jQuery 1.4.3, .data( obj ) completely replaced all data. Since jQuery 1.4.3, data is instead extended by shallow merge."
font: jquery documentation
:)
Upvotes: 1
Reputation: 779
Regarding HTML5 data-* attributes: This low-level method does NOT retrieve the data-* attributes unless the more convenient .data() method has already retrieved them.
The jQuery.data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. We can retrieve several distinct values for a single element one at a time, or as a set.
You can refer this link for more details. I hope this can help you.
Upvotes: 0
Reputation: 2664
One use case can be around storing instance, pseudo code below
function SomePlugin(element, options) {
this.$el = $(element);
this.options = options;
}
SomePlugin.prototype.method = function() {
this.$el.toggleClass(this.options.cssClass);
}
$.fn.somePlugin = function(options) {
var somePluginInstance = new SomePlugin(this, options);
// store instance as data
this.data("somePlugin", somePluginInstance);
}
usage:
$(".element").somePlugin({});
var pluginInstance = $(".element").data("somePlugin");
pluginInstance.method();
Upvotes: 1