17

I use data attributes extensively for managing data in client side events. Is it possible to assign value dynamically to a data attribute using javascript or jquery?

<li data-class_value="somevalue" class="myclass"></li>


$('.myclass').click(function(){
   $(this).data('class_value') = "new value";
});

The above javascript code throws the error:

"Uncaught ReferenceError: Invalid left-hand side in assignment".

Could someone please tell me how this can be achieved?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Abishek
  • 11,191
  • 19
  • 72
  • 111

3 Answers3

32

I believe the answers above would only set the data object on that element within jQuery.

If you need to set the actual HTML data-* attribute, you'd need to use this:

$(this).attr("data-class_value", "new value");

Beware of retrieving HTML5 data-* attributes this way as well, as although you can use the shortcut $(this).data("class_value"); to retrieve them, subsequent retrievals will use the cached value in the jQuery data object.

From the jQuery docs:

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

Source: jQuery caching of data attributes

jjeaton
  • 926
  • 2
  • 14
  • 26
  • 3
    That caching of data attributes ate few hours, thanks! – Alexander Kim Dec 12 '14 at 12:16
  • How do you work around that caching issue? I tried `$(this).removeAttr("data-class_value", "new value");` but of course it doesn't work. Any clues? – kevllar Aug 19 '15 at 04:03
  • @kevllar `removeAttr` only takes one argument. So it won't set the new value for you. You'd need to use `attr` instead. – jjeaton Aug 19 '15 at 15:53
  • @jjeaton I'm trying to set the attribute then remove it... But its not working because its being cached... I tried `attr` but no joy – kevllar Aug 19 '15 at 18:21
  • @kevllar if you want to remove the data from the cache AND remove the attribute in the DOM, you'd want this: `$(this).removeData("class_value").removeAttr("data-class_value")` – jjeaton Aug 19 '15 at 18:50
  • @jjeaton Looks like I wasn't targeting the dom elements correctly. I used `attr` and then `removeAttr` and that seemed to work in the end. No need for removeData. Thanks! – kevllar Aug 20 '15 at 14:52
23

You need to do

 $(this).data('class_value', "new value");
Dogbert
  • 212,659
  • 41
  • 396
  • 397
2

$(this).data('class_value','new value') ;

.data

Rafay
  • 30,950
  • 5
  • 68
  • 101