I would like to give a complementary information to @Sergio's answer, so there goes another "comment comment".
Let's suppose that in your HTML
it has an element with a data custom attribute (data-*)
similar to the following:
<div id="helloWorld" data-nome="Hello World!"></div>
In jQuery you can access the value of this property in two ways:
var helloWorld = $("#helloWorld");
var usingAttr = helloWorld.attr("data-nome");
var usingData = helloWorld.data("nome");
console.log(usingAttr); //saida: "Hello World!"
console.log(usingData); //saida: "Hello World!"
<div id="helloWorld" data-nome="Hello World!" ></div>
But if you make a set using .data("nome", value)
, it will update the value only on the data object, however it will not update the date attribute value, as in the example below:
var helloWorld = $("#helloWorld");
helloWorld.data("nome", "Hello Mars?");
var usingAttr = helloWorld.attr("data-nome");
var usingData = helloWorld.data("nome");
console.log(usingAttr); //saida: "Hello World!"
console.log(usingData); //saida: "Hello Mars?"
<div id="helloWorld" data-nome="Hello World!" ></div>
But if you make a set using .attr("data-nome", value)
, then the value of the object and date attribute will be updated:
var helloWorld = $("#helloWorld");
helloWorld.attr("data-nome", "Hello Mars?");
var usingAttr = helloWorld.attr("data-nome");
var usingData = helloWorld.data("nome");
console.log(usingAttr); //saida: "Hello Mars?"
console.log(usingData); //saida: "Hello Mars?"
<div id="helloWorld" data-nome="Hello World!" ></div>
Finally, if you wanted to access a data custom attribute (data-*)
that has a compound name using the .data()
method, you will have to remove the hyphens and change the name to pascalCase, but using .attr()
nothing changes:
var helloWorld = $("#helloWorld");
var usingAttr = helloWorld.attr("data-nome-completo");
var usingData = helloWorld.data("nomeCompleto"); //Pascal Case
console.log(usingAttr); //saida: "Hello World!"
console.log(usingData); //saida: "Hello World!"
<div id="helloWorld" data-nome-completo="Hello World!" ></div>
This is because the .data()
method was created before specifying the data custom attribute (data-*)
and can be used to store any type of object (string, integer, float, Date, JSON, etc.), whereas an attribute can store only text (string).