Yesterday, one of my co-workers came to me perplexed. He couldn't understand why his
.data() call was returning a different value than the current value of attribute. He is not a novice to jQuery, but he made the same mistake that many developers do in their first few years using jQuery: he didn't read the documentation AND the source code for the
What my co-worker did not know is that the
.data() method caches the value of the data-attribute, and any subsequent calls to
.data() read from the cache and not the actual attribute. Instead, he thought that the
.data("foo") call was just short for
In short, the
.data() method should be used for accessing data-attribute values if and only if the value of that data-attribute is not going to be changed. In all other situations, the
.attr() attribute should be used. Note that jQuery's
.data() method is not meant to be used for manipulating/setting attribute values. As such, a general rule of thumb is to always use
.attr() for both getting and setting whenever a data attribute's value is going to be manipulated.
Note that the documentation for jQuery's
.data() method does not mention the caching functionality of the method, but it is there and can be seen in the source code of the method.
Know What You are Writing
When writing code, the developer should always know what it is that they are writing. It is understandable that mistakes will be made, but developers should always take the extra minute to research the code that they use. Knowing the methods and the language's syntax is not enough; even reading the documentation for the language is not enough.
Just to include a few examples in regards to documentation, to truly know what it is that they are writing, developers must at least know what the strengths and weaknesses of the documentation are; they must know when documentation for a language tends to be incomplete or insufficient, what kinds of things are occasionally left out, when the developers of the language update the documentation, and when the amount of information provided is less than normal.
When anything seems different or out of place, the developer needs to know to and where to seek further reliable information about the code. The documentation for jQuery's
method does not mention the caching functionality of the method, but it also does not mention the
method at any point, which it almost always does when two methods do the same or nearly the same thing. This should be a red flag to the developer and lead him or her to investigate the source code for the method before using it.