Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Created November 19, 2020 19:38
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save WebReflection/41ec092ff5ea12ba8687d62df839e43d to your computer and use it in GitHub Desktop.
Save WebReflection/41ec092ff5ea12ba8687d62df839e43d to your computer and use it in GitHub Desktop.
A dataset like behavior for any attribute
const proxies = new WeakMap;
const hyphen = name => name.replace(/([a-z])([A-Z])/g, '$1-$2');
const handler = {
get: (el, name) => el.getAttribute(hyphen(name)),
set: (el, name, value) => {
el.setAttribute(hyphen(name), value);
return true;
}
};
const set = el => {
const proxy = new Proxy(el, handler);
proxies.set(el, proxy);
return proxy;
};
const attr = el => proxies.get(el) || set(el);
attr(document.body).itemprop = 1;
attr(document.body).ariaDescribedby = 'id';
document.body.outerHTML;
/*
<body itemprop="1" aria-describedby="id"></body>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment