3

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.

1
  • please add some real code with explanation of error so that we can help. Commented Mar 20, 2021 at 21:10

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.