what does jQuery data() function do
It allows you to associate any type of data with a DOM element. See this blog post for some examples.
Its really useful for associating various objects, strings, arrays, etc with a DOM element. Here is a fun hypothetical use:
$(document).ready(function(){
$("a").each(function(index, el){
if(index % 2 == 0)
$(this).data('coolColor', 'Orange'); // Set the data
else
$(this).data('coolColor', 'Purple'); // Set the data
}).click(function(e){
alert($(this).data('coolColor')); // Retrieve the data
e.preventDefault();
});
});
This would select every a
tag, and set Orange
if its odd, or Purple
if its even. This is not the most optimal way to write this code if this is what you really wanted to do, but it does illustrate how to use the .data()
function.
You can also use it to store objects:
$("#header").data('headerSettings',{
color: "red",
cost: "$25.00",
time: 1000
});
Now you could access that data anywhere else on the page:
$("#header").data('headerSettings').color;
I think this question needs a bit more attention. jQuery's data
API is really powerful for various use-cases.
jQuery's data function allows you to store and retrieve any associated data with any jQuery object.
Primarily, it can also be used to read data-
attributes set on any node in the html.
Example 1
HTML:
<div id="myNode" data-foo="bar"></div>
.
jQuery Code:
$("#myNode").data("foo") //bar
Example 2
Likewise I can store a value w.r.t any node too.
jQuery Code:
$("#myNode").data("foo","baz")
$("#myNode").data("foo") //baz
One important thing to note here is, that when one sets a data on the note using the data API, the html is not updated in the DOM. If you want to update the HTML, you might want to stick to the attr("data-foo","baz")
method.
While one can read strings stored in HTML data attributes, you can also assign an object while storing a value using the data API.
There are various use-cases where developers link an object with a node.
e.g.
var obj = {
name : "test"
}
$("#myNode").data("foo",obj);
$("#myNode").data("foo") === obj //true
Go ahead, explore the API here.