What's the reason for storing data with .data() instead of using plain variables?

Let's say I have to remember the initial height of certain element. A common practice I see is to save this value with $.data on that element.

I fail to understand the benefits of this. Why not simply keep a simple variable with that value, or an array with values if there are multiple elements? Keeps the code easy to understand.



It allows the function to be reused to apply the same effect to other elements (without having to deal with closures).

It allows the value to be initialized with HTML.

It makes it easier for developer tools to inspect the data.


The main reason for using data() is to store data specific to a certain element so it can be accessed later, here's an example

$('.elements').on('click', function() {
     $(this).data('value', this.value);

$('.elements').on('keyup', function() {
    $(this).val( $(this).data('value') );

Note that the event handler could match a number of different elements, and using data() keeps the data associated to each element without using several variables for each element or a complex array.



Basically because le you save information INSIDE A NODE, preventing possible variable name conflicts and without the need to pass variables around. All the needed informations about a node, stay with the node itself


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.