If you try to change a data attribute value with data() method you don’t get the same result as attr(data-key, data-value) method.
For example, I’m using data-hovered=true to store some state for the element. If you have some css styling for the element[data-hovered=true] selector, using data() method to assing the value true to data-hovered won’t have effect. Only using attr() this would have effect.
So what’s the difference between these two methods?
.data() is used to store data in an object, but as of the “release” of HTML5, it can also access data-* attributes on elements.
However, it can not change these, as it is primarily used for storing data in objects etc, not physically on elements.
Therefore attr() is the only way to change a value of an attribute on an element, such as data-* attributes.
See: