Note that there is a difference between updating or applying a data
attribute using the jQuery method .attr()
and the method .data()
.
The examples below can be seen in this JSFiddle .
-
Apply value to non-existent attribute
If you apply the value using the
.attr()
method and then change it using the.data()
method, the result in collecting the value varies according to the method used to apply it:<div id="myBanana"></div>
-
Apply
// utilizando .attr() $( "#myBanana" ).attr( "data-fail", "no banana" ); // utilizando .data() $( "#myBanana" ).data( "fail", "no monkey" );
-
Collapse
// utilizando .attr() da "no banana" console.log( $( "#myBanana" ).attr( "data-fail" ) ); // utilizando .data() dá "no monkey" console.log ( $( "#myBanana" ).data( "fail" ) );
-
-
Apply value to existing attribute
If the attribute already exists in the element, when collecting it with any of the methods, I get the existing value.
After making a change to the value, depending on the method used, the applied value is only correctly collected if you use the same method to get it:
<div id="myMonkey" data-fail="banana"></div>
-
Collapse
// utilizando .attr() dá "banana" console.log( $( "#myMonkey" ).attr( "data-fail" ) ); // utilizando .data() dá "banana" console.log ( $( "#myMonkey" ).data( "fail" ) );
-
Change
// utilizando .attr() $( "#myMonkey" ).attr( "data-fail", "No banana" ); // utilizando .data() $( "#myMonkey" ).data( "fail", "More banana" );
-
Retrace
// utilizando .attr() dá "No banana" console.log( $( "#myMonkey" ).attr( "data-fail" ) ); // utilizando .data() dá "More banana" console.log ( $( "#myMonkey" ).data( "fail" ) );
At the start both methods were collecting the same value that was already present in the
data
attribute, but after changing this value, I have to use the same method to apply and collapse values or diverge results. -
It is obvious that the fact that the attribute is called data-*
is not directly related to the .data()
method, but to the .attr()
method.
In addition, both methods seem to interact with the data
attribute to a certain extent, but each has its way of saving new assigned values.
In analyzing what happens in terms of manipulation of the DOM, there are also visible differences in substances caused by the use of each of the methods:
The .attr()
method is actually updating the value of the data
attribute while the .data()
method does not affect the value of the attribute, rather it attaches an identifier with its value to the element.
Question
What is the difference between the .attr()
method and the .data()
method in terms of usage, purpose, and impact on the element, to make use of the arbitrary data assignment that HTML5 provides?