I would like to give a complementary information the reply of @Sergio, so there goes another "reply comment".
Let’s assume that in your HTML
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 in the date object, but will not update the value of the date attribute, 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-*)
which has a compound name using the method .data()
, you will have to remove the hyphens and turn the name into pascalCase, however 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 method .data()
was created before the specification of data custom attribute (data-*)
and can be used to store whatever type of object (string, integer, float, Date, JSON, etc.), while an attribute can store only text (string).
Hello @Sergio, thank you so much for the excellent tip and even more for making the example available, thank you.
– adventistapr