I just racked my brain for the past hour trying to fix a bug, and learned something new in the process.
I always thought that the jQuery function .data('key')
was a wrapper for .attr('data-key')
. It turns out that's not the case!
Take the example: <div data-key="foo">
:
I can use data('key', 'foo')
to set data-key
to something in the DOM. I can use data('key')
to retrieve the value of the data. I can also use attr('data-key')
to retrieve the value of the data.
It turns out the data()
method has a cache, and once a value is set, anytime you use .data()
to retrieve it, it's always retrieved from the cache. When using the attr()
method, it's always retrieved from the latest value in the DOM.
Just thought I'd pass this on.