Created
March 3, 2019 02:48
-
-
Save msand/b658769fe37586c2eb269cc8bdae5fbf to your computer and use it in GitHub Desktop.
inline css to svg attributes
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 camelToKebab = camel => camel.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); | |
/* Inline all rules from all CSS stylesheets as attributes | |
on all matching elements and remove class attribute */ | |
const styles = Array.from(document.querySelectorAll("style")); | |
styles.forEach(styleSheet => { | |
Array.from(styleSheet.sheet.cssRules).forEach(rule => { | |
if (rule.style.display === "none") { | |
// Remove hidden elements | |
Array.from(document.querySelectorAll(rule.selectorText)).forEach(el => { | |
el.parentElement.removeChild(el); | |
}); | |
} else { | |
const styles = Object.entries(rule.style).filter(([key, value]) => key !== "cssText" && isNaN(+key) && value); | |
Array.from(document.querySelectorAll(rule.selectorText)).forEach(el => { | |
styles.forEach(([key, value]) => { | |
el.setAttribute(camelToKebab(key), value); | |
}); | |
}); | |
} | |
}); | |
}); | |
styles.forEach(styleSheet => { | |
Array.from(styleSheet.sheet.cssRules).forEach(rule => { | |
Array.from(document.querySelectorAll(rule.selectorText)).forEach(el => { | |
el.removeAttribute("class"); | |
}); | |
}); | |
styleSheet.parentElement.removeChild(styleSheet); | |
}); | |
/* Move inline CSS style values into element attributes */ | |
Array.from(document.querySelectorAll("[style]")).forEach(el => { | |
Object.entries(el.style).forEach(([key, value]) => { | |
if (key !== "cssText" && isNaN(+key) && value) { | |
el.setAttribute(camelToKebab(key), value); | |
} | |
}); | |
el.removeAttribute("style"); | |
}); | |
Array.from(document.querySelectorAll("g")).forEach(el => { | |
if (el.innerHTML.trim() === "") { | |
el.parentElement.removeChild(el); | |
} | |
}); | |
const svg = document.querySelector("svg"); | |
Array.from(svg.attributes).forEach(attr => { | |
if (attr.name === "xmlns:xlink") { | |
svg.removeAttributeNode(attr); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment