Skip to content

Instantly share code, notes, and snippets.

@mindon
Created November 3, 2022 07:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mindon/53a24eda095545c2fcda8029fa44dc41 to your computer and use it in GitHub Desktop.
Save mindon/53a24eda095545c2fcda8029fa44dc41 to your computer and use it in GitHub Desktop.
use (selector) in class to reuse classes from first element of selector
// (selector) in class to reuse classes from first element of selector
// define a class-ref <div id="my" class="a b c d"></div>
// use class ref <div class="ref x y (#my) z"></div>
// result in <div class="ref x y a b c d z"></div>
function refClass(root) {
[].slice.apply((root || document).querySelectorAll('.ref')).forEach(d => {
const c = d.className.replace(/\([:#.]?[\w.-]+\)/g, (s) => {
const q = s.charAt(1) == ':'
? `[class-ref="${s.substr(2, s.length - 3)}"]`
: s.substr(1, s.length -2);
const t = document.querySelector(q);
return t && t.className || '';
});
if (c != d.className) {
d.className = c;
}
});
}
window.addEventListener('DOMContentLoaded', () => refClass());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment