Skip to content

Instantly share code, notes, and snippets.

@franktopel
Last active September 17, 2020 11:39
Show Gist options
  • Save franktopel/be4c5a07281b6715a010fe0361582427 to your computer and use it in GitHub Desktop.
Save franktopel/be4c5a07281b6715a010fe0361582427 to your computer and use it in GitHub Desktop.
Javascript function to extract 'unsafe-inline' styles from a HTML string
export function separateHtmlAndCss(str) {
const parser = new DOMParser();
let parsedHtml = parser.parseFromString(str, 'text/html');
const CLASS_NAME_PREFIX = 'generated-class-name-';
let html, css = '';
// handle <style>-Tags
const styleTags = parsedHtml.querySelectorAll('style');
if (styleTags.length > 0) {
for (let i = 0; i < styleTags.length; i++) {
css = css.concat(styleTags[i].textContent);
styleTags[i].remove();
}
}
// handle style-Attributes <el style="...">
const elementsWithStyleAttributes = parsedHtml.querySelectorAll('[style]');
if (elementsWithStyleAttributes.length > 0) {
for (let i = 0; i < elementsWithStyleAttributes.length; i++) {
let generatedClassName = CLASS_NAME_PREFIX.concat(i);
css += `.${generatedClassName} {
${elementsWithStyleAttributes[i].getAttribute('style')}
}\n`;
elementsWithStyleAttributes[i].classList.add(generatedClassName);
elementsWithStyleAttributes[i].removeAttribute('style');
}
}
// extract the body's innerHTML
html = parsedHtml.body.innerHTML;
// and return it alongside the extracted CSS
return { html, css };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment