0

Say,

<a id="link-one" href="#" data-status="true">Anchor</a>

The following code writes "true" on the console:

console.log($('#link-one').data('status'));

And, when I change the value like this:

$('#link-one').attr('data-status', 'false');

the value changes, and I can see that by inspecting the element with Chrome inspector. Yes, it really is changing.

However, after assigning/changing the value like above and then accessing it again after changes returning me the initial value, not the modified new value. I need to access the current value, that is after changes.

console.log($('#link-one').data('status'));  // writes "true"
$('#link-one').attr('data-status', 'false');
console.log($('#link-one').data('status'));  // writes "true" again

Am I missing something? Or this is default behavior of jQuery (if yes, how can I achieve what I need)?

gurudeb
  • 1,856
  • 22
  • 29
user3332579
  • 3,111
  • 3
  • 17
  • 21
  • 1
    Data attributes and data object properties are not the same. Jquery parse data attributes to data object property only when parsed the first time. You should use then `$('#link-one').data('status', false);` Be aware than string `'false'` is evaluated as true in javascript, i guess you want a boolean – A. Wolff May 14 '14 at 15:42
  • 1
    `attr` is for DOM atributes. `href`, `src`, `class`, etc.. `data` is completely separate and not related. – Marc B May 14 '14 at 15:43
  • 1
    You should use `data()` as both the getter and the setter. – Rory McCrossan May 14 '14 at 15:45

1 Answers1

6

The data-attribute are parsed the first time jQuery will access it, and default when the document is loaded.

If you want to set the data value to false you have to do this:

$("#link-one").data("status", false);

And than you can access it by:

$("#link-one").data("status"); // False now

Quote:

Regarding HTML5 data-* attributes: This low-level method does NOT retrieve the data-* attributes unless the more convenient .data() method has already retrieved them.

Which means, once parsed, it won't parse it again.

Niels
  • 48,601
  • 4
  • 62
  • 81