Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a div data attributes with javascript if the dataset name has more than one dash?

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

like image 697
elixireu Avatar asked Feb 06 '23 14:02

elixireu


1 Answers

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">
like image 196
Ramiz Wachtler Avatar answered Feb 08 '23 03:02

Ramiz Wachtler