I have a custom data-attribute set by default:
data-equipment="0"
If i change it with jquery using .data()
$(this).data("equipment", 10)
and then use the getAttribute()
this.getAttribute("data-equipment")
i get the old value (0) and not the new one (10). But if i use
$(this).data("equipment")
i get the new value (10).
Is this supposed to work like this or am i missing something?
Thanks!
To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).
To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written.
The data-* attribute gives us the ability to embed custom data attributes on all HTML elements. The stored (custom) data can then be used in the page's JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).
on('click', function (e) { var id = $(e. target). attr('id'); console. log(id); });
.data()
doesn't operate on data attributes but in internal jQuery cache. Initially if no cache record is found, the data is read from a corresponding data-
attribute if one exists, but that is the end of their co-operation.
If it operated on attributes, it would be useless for its purpose because attribute values must be strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With