I need to update a div layer's dataset with javascript. The below code is working if the dataset has one dash e.g. data-myvar
...
<div id="myDiv" data-myvar="10">
var theDiv = document.getElementById("myDiv");
theDiv.className = 'newClass';
theDiv.dataset.myvar = '20';
theDiv.appendChild(content);
gives the result
<div id="myDiv" data-myvar="20" class="newClass">
works great, but when I have a dataset such as data-myvar-list
it doesn't work. I have tried for example
theDiv.dataset.myvar.list = '20';
And this which gives a syntex error
theDiv.dataset.myvar-list = '20';
any ideas?
Thanks
You could also use theDiv.dataset.myvarList
, the dash gets replaced by camel-case.
dash-style to camelCase: A custom data attribute name is transformed to a key for the DOMStringMap entry with the following rules
- the prefix data- is removed (including the dash);
- for any dash (U+002D) followed by an ASCII lowercase letter a to z, the dash is removed and the letter is transformed into its uppercase counterpart;
- other characters (including other dashes) are left unchanged.
You can read more about it here --> source - MDN
Check out the following snippet
var theDiv = document.getElementById("myDiv");
theDiv.className = 'newClass';
console.log(theDiv.dataset.myvarList);
<div id="myDiv" data-myvar-list="20" class="newClass">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With