I am changing the data-demo
attribute of a div
element and when I want to check it with in another event, it always shows me the initial value of it instead of the current value.
This is the code I am using:
$('#showValue').click(function(){
alert($('.value').data('demo'));
});
$('.update').click(function(){
$('.value').text('updated').attr('data-demo', 'updated');
});
Why is this happening?
Here's a fiddle with the example I am talking about: http://jsfiddle.net/f5Cpm/
Thanks.
JavaScript access 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. In the above case setting article. dataset.
The prop() method sets or returns properties and values of the selected elements. When this method is used to return the property value, it returns the value of the FIRST matched element. When this method is used to set property values, it sets one or more property/value pairs for the set of matched elements.
In short, a data attribute is a single-value descriptor for a data point or data object. It exists most often as a column in a data table, but can also refer to special formatting or functionality for objects in programming languages such as Python.
Definition and Usage The data-* attribute is used to store custom data private to the page or application. The data-* attribute gives us the ability to embed custom data attributes on all HTML elements.
After the internal data is first initialized, it never goes back to the attribute to get or set the value, therefore updating the attribute will not update what is stored in .data() if you've already used .data on that element.
Read more here
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