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:

    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:

    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.