Search code examples
javascriptjquerycustom-data-attributejquery-data

Getting different results from attribute.dataset and jquery .data() method


I was getting unexpected results and when I debugged into the problem, I found that I was not getting right data-attribute value by Jquery .data() method. It was pretty clear that value was not right and when I changed my code to attribute.dataset.name (native property of an element) It returned me the expected value.

here's the screenshot of an error

Any ideas, what could be the possible reason because I am using a lot of data-attributes in my situation and don't want to change the code everywhere I am accessing data-attributes by Jquery .date() method.


Solution

  • .data(prop) and .dataset[prop] can be different if:

    • The HTML dataset contains one value

    • jQuery's .data has been called on the element previously to store a value associated with the same key

    Example:

    $('div').data('foo', 'newFooVal');
    
    console.log($('div').data('foo'));
    console.log($('div')[0].dataset.foo);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div data-foo="oldFooVal"></div>

    jQuery's .data will retrieve:

    • Any previous value set with .data (which will be completely unrelated to the dataset)

    • If no previous value has been set to that key with that element, the value for that key in the dataset will be returned

    So you have to be careful with what setting and retrieving. It's admittedly not entirely intuitive, since it'll do something different in different situations.