dataset attributes – get/set correct camel case name

  • A+
Category:Languages

I have attribute names stored somewhere in a string and need a way to create corrected names to use with dataset api. I get the names of those in attribute style, like data-attrib-name. So I need to convert them to camel case and remove the data- in front of it.

The shortest way I found out for now is my replace below. But this feel kinda hacky to me. Is there a better solution / shorter way for my task?

console.log(   "data-my-test-name"     .replace('data-', '')     .replace(/-([a-z]?)/g, (m, g) => g.toUpperCase()) );

 


You can use setAttribute with the attribute directly without using the dataset

var attr = "data-attrib-name"; document.getElementById("f1").setAttribute(attr,"changed");  

Various methods:

console.log(document.getElementById("f1").dataset); var attr = "data-attrib-name";  document.getElementById("f1").setAttribute(attr,"changed"); // set the attribute  console.log(document.getElementById("f1").dataset);  var datasetByAttr = document.querySelector("["+attr+"]").dataset; console.log(datasetByAttr);
<input type="text" id="f1" data-set-name="set" data-attrib-name="attr"/>

If you MUST use camelCase, you can use the dataset on an element you create;

var attr = "data-attrib-name",     test = document.createElement("span");  test.setAttribute(attr,1) var camelCase = Object.keys(test.dataset)[0]; test = null; console.log(camelCase);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: