Skip to content

Instantly share code, notes, and snippets.

@mattdanielbrown
Forked from WebReflection/attr.js
Created December 14, 2021 18:33
Show Gist options
  • Select an option

  • Save mattdanielbrown/d7326c859f9e4c39d243a667fe6effbf to your computer and use it in GitHub Desktop.

Select an option

Save mattdanielbrown/d7326c859f9e4c39d243a667fe6effbf 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