javascriptjqueryjquery-data

Setting a value dynamically for data attributes using jquery


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?


Solution

  • You need to do

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