Created
November 19, 2020 19:38
-
-
Save WebReflection/41ec092ff5ea12ba8687d62df839e43d to your computer and use it in GitHub Desktop.
A dataset like behavior for any attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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