Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 562
Hamza Shamshad Avatar asked Jan 24 '26 16:01

Hamza Shamshad


1 Answers

.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.

like image 82
CertainPerformance Avatar answered Jan 27 '26 06:01

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!