Although there are some examples about this on the web, it does not seem to work correctly. I can\'t figure out the problem.
I have this simple html
This answer is for those seeking to just change the value of a data-attribute
The suggested will not change the value of your Jquery data-attr correctly as @adeneo has stated. For some reason though, I'm not seeing him (or any others) post the correct method for those seeking to update their data-attr. The answer that @Lucas Willems has posted may be the answer to problem Brian Tompsett - 汤莱恩 is having, but it's not the answer to the inquiry that may be bringing other users here.
Quick answer in regards to original inquiry statement
-To update data-attr
$('#ElementId').attr('data-attributeTitle',newAttributeValue);
Easy mistakes* - there must be "data-" at the beginning of your attribute you're looking to change the value of.
Basically, there are two ways to set / update data attribute value, depends on your need. The difference is just, where the data saved,
If you use .data()
it will be saved in local variable called data_user
, and its not visible upon element inspection,
If you use .attr()
it will be publicly visible.
Much clearer explanation on this comment
Had a similar problem, I propose this solution althought is not supported in IE 10 and under.
Given
<div id='example' data-example-update='1'></div>
The Javascript standard defines a property called dataset to update data-example-update.
document.getElementById('example').dataset.exampleUpdate = 2;
Note: use camel case notation to access the correct data attribute.
Source: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes