22

I am updating a data attribute by jQuery, Like:

jQuery('div').data('hidden', 'true');
alert(jQuery('div').data('hidden'));

Data attribute value got changed and returned new value which is true but DOM is still showing the old value which is false.

user007
  • 3,203
  • 13
  • 46
  • 77

2 Answers2

40

When you use .data() to update a data value, it is updating internal object managed by jQuery, so it will not be updated in the data-* attribute

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 1
    @HowToPlease yes, attr() updates the dom attribute, both of the serves different purposes. – Arun P Johny Jul 16 '13 at 03:57
  • why do you want the element attribute to be updated in the first place – Arun P Johny Jul 16 '13 at 03:58
  • I was using data attribute for else if, I seen that data is not updating, but when I did `alert` then it shows the updated value. – user007 Jul 16 '13 at 04:01
  • 1
    I also faced the same problem, using attr() solved the problem. I dont know why jquery managing a object instead of injecting it in the DOM :( – www.amitpatil.me Oct 10 '14 at 08:15
  • Is there any noticeable problems that could be encountered by the fact that the added data attributes are not visible in the dom? Jquery finds them just find when you use jquery to search for them. – Andrew Sep 25 '15 at 18:59
  • @Andrew no.... it wont show up because jQuery saves it in an internal data structure... not using the native data api. – Arun P Johny Sep 26 '15 at 04:22
5

I was beating around the bush so badly :( and able to solve the problem. Seams like we can't do achieve this using the jquery data method if the html is dynamic and the data attribute changed later after accessing the first time.

According to jQuery.data()

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

So what I did is, changed it to attr method which won't give you the parsed value for integer, so you have to use '+' operand to convert like:

+ myElement.attr('data-index');

Note: You have to be careful, it will convert the result to NaN if there is any string in the data attr. BTW it's your choice of implementation of the code.

Mahavir
  • 322
  • 4
  • 8