-
-
Save mattdanielbrown/d7326c859f9e4c39d243a667fe6effbf to your computer and use it in GitHub Desktop.
A dataset like behavior for any attribute
This file contains hidden or 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