Is it possible and smart to store extra data inside a jQuery object?
Right now I have objects that contain some data but these objects also have a visual representation of that data. This works but I have a lot of code to keep them both in sync.
For example if you delete an object from the dom I also have to delete the related object from the object array. Deleting is fairly simple but it gets a little more complicated if I start sorting/moving the objects around.
You can use
$.data()for this 🙂For example:
Or use the object method
.data():This doesn’t store the data on the object, rather it stores it in
$.cache(try it in your console on this page), but it’s associated with the object, viathis[$.expando].However if you call
.empty()that removes an object, or.remove(), it’ll do the cleanup for you. You can also call.removeData()or$.removeData()to remove it directly.