JSFiddle - React, Tailwind, and code Playground
HTML
<div id="x" data-given-name="Fred" data-surname="Flintstone" data-city="Bedrock" data-city-description="A land right out of history" data-spouse-given-name="Wilma"></div>
CSS
#x {
white-space: pre-wrap;
font-family: consolas, monospace;
font-size: 14px;
}
JavaScript
function setDataAttributes(el, data) {
Object.keys(data).forEach(function (key) {
var attrName = "data-" + key.replace(/[A-Z]/g, function ($0) {
return "-" + $0.toLowerCase();
});
el.setAttribute(attrName, data[key]);
});
}
onload = function (e) {
var el = document.getElementById("x");
var data = {
givenName: "Barney",
surname: "Rubble",
city: "Bedrock",
cityDescription: "A land right out of history",
spouseGivenName: "Betty"
};
setDataAttributes(el, data);
var html = document.body.innerHTML.trim();
el.appendChild(document.createTextNode(html));
};