I know its bad to store data in the DOM, but why?

It’s fine to store data in DOM objects. And since your question is specific to jQuery’s data API, it’s important to understand how the data API works. I wrote an answer explaining its inner workings a while back. The data API only keeps a reference to the DOM objects along with the data, and doesn’t store anything inside the DOM objects themselves. All data is stored in plain old JavaScript objects.

The issue of whether that is a good or a bad approach is a matter of personal taste. John Resig, the creator of jQuery, gave a talk at Tech4Africa in 2010 where he talks about this exact issue, and proposes to do away with a separate storage area and link everything with the DOM using the data API. You can see the talk on YouTube (thanks to @tine2k for providing the link). If you listen to the entire talk, you’ll find some good examples of why this approach makes sense and keeps things simple.

I believe similar arguments can be made for the other end of the spectrum – to have your data in neatly tucked away objects, and classes, and be separate from the view itself. That sort of thinking comes from traditional architectures such as MVC.

I say it’s fine to go with either approach – using the DOM to store data, or using a classical approach. Just don’t mix the two, cause then you application model is sprinkled everywhere.

Leave a Comment