0

When i edit a DOM element with jQuery.data function, DOM code is not really updated:

Ex, for:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
  <div id="foo" data-price="100">Foo</div>
</body>
</html>

And:

console.log($('#foo').data('price'));
$('#foo').data('price', 90);
console.log($('#foo').data('price'));
console.log('[data-price=90]: ' + $('[data-price=90]').length);
console.log('[data-price=100]: ' + $('[data-price=100]').length);

Output is:

100
90
"[data-price=90]: 0"
"[data-price=100]: 1"

(This exemple is available here)

So, after jQuery.data usage, div#foo still have 90 as price. How to really modify it with jQuery method ?

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
bux
  • 7,087
  • 11
  • 45
  • 86
  • Please use `$(element).data({key:value}); //to set data` and `$(element).data(key); // to get data` I understand what you are trying to seek but the dom might not be updated and data tag generally works behind the scenes – joyBlanks Aug 11 '15 at 15:35
  • I'm not sure if .data( ) method allows for changing the property value inside *.html. Read more: https://stackoverflow.com/questions/17762906/cant-update-data-attribute-value-jquery – misko321 Aug 11 '15 at 15:36

2 Answers2

0

One solution is to modify attribute to:

console.log($('#foo').data('price'));
$('#foo').attr('data-price', 90);
$('#foo').data('price', 90);
console.log($('#foo').data('price'));
console.log('[data-price=90]: ' + $('[data-price=90]').length);
console.log('[data-price=100]: ' + $('[data-price=100]').length);

Will output:

100
90
"[data-price=90]: 1"
"[data-price=100]: 0"
bux
  • 7,087
  • 11
  • 45
  • 86
0

@bux is on point because, as you can see from here:

Note that .removeData() will only remove data from jQuery's internal .data() cache, and any corresponding data- attributes on the element will not be removed. A later call to data() will therefore re-retrieve the value from the data- attribute. To prevent this, use .removeAttr() alongside .removeData() to remove the data- attribute as well. Prior to jQuery 1.4.3, as data() did not use data- attributes, this was not an issue.

Thus, there's the cached data, which can be manipulated by using .data() and there's the corresponding data- attribute.

When you change the cached data via .data('price', 90), the attribute data-price="100" is still intact and does not get changed.

PeterKA
  • 24,158
  • 5
  • 26
  • 48