4

I have an weird issue with jquery data function. Here is the fiddle

As you can see I update the active data but I cannot see the dom data-active attribute value change, although I re-query the active data, It writes the changed value. $.data() do not update the attribute on the dom when I inspect it.

Community
  • 1
  • 1
px5x2
  • 1,495
  • 2
  • 14
  • 29
  • 1
    `.data()` and attributes are not the same thing. jQuery just happens to make all `data-*` attributes available by `.data()`. If you manipulate `.data()`, it doesn't change the attribute. If you manipulate the attribute, it does change the `.data()`. Also, just as a note, instead of `$($('li')[1])`, you can use `$("li").eq(1)` - you don't have to re-wrap it in a jQuery object – Ian Jun 17 '13 at 13:45
  • I always just use `.attr('data-'+data,value)` and `.attr('data-'+data)`. – SeinopSys Jun 17 '13 at 13:45
  • http://stackoverflow.com/a/7262427/1414562 – A. Wolff Jun 17 '13 at 13:48

2 Answers2

6

jQuery data api does not depends on the element attribute although it uses data-<key> to fetch the initial value if it is available.

jQuery uses an internal javascript object to maintain the data value of objects

If you want to update the attribute then you will have to use .attr('data-<key>', '<value>')

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Appreciated for explanation. However, what is the point of using `.data` function then? I can query but not update, this inconsistency can create weird behaviours for inexperienced users of jq. I'd rather use the very same function for both query and update. Is there a reasonable explanation for that? – px5x2 Jun 17 '13 at 13:57
  • @px5x2 you can update as well as query the data :) only problem is the attribute value will not get updated, the updated value is stored as a key-value construct by jQuery – Arun P Johny Jun 17 '13 at 16:27
2

You will need to use attr as .data will not update the actual DOM node attribute -

$($('li')[1]).attr('data-active', true);
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111