I have a simple setup with an attribute 'data-id' attached to the element:
<div class='row' data-id='1'>
If I call alert($(.row).data(id));
I will get my id 1.
Next thing I change this id manually or via another script to, say, 2:
<div class='row' data-id='2'>
and now if I call alert($(.row).data(id));
I still will get 1 instead of 2.
However, if I change method .data()
to attr('data-id')
the result gonna be 2.
What is the reason of such behavior?
The reason is because jQuery stores all data
attribute key/value pairs in an object, separate from the DOM. The data()
method reads from this object.
When you update the data
attribute using attr()
you update the DOM only, hence the data()
method reads the old value from the in memory object.
For this reason it's always best to use data()
as both the setter and getter.
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