Skip to content

Instantly share code, notes, and snippets.

@Musinux
Created July 4, 2018 07:48
Show Gist options
  • Select an option

  • Save Musinux/96a8177daa53d46ab3ea89962d3081c2 to your computer and use it in GitHub Desktop.

Select an option

Save Musinux/96a8177daa53d46ab3ea89962d3081c2 to your computer and use it in GitHub Desktop.
Node.js implementation of transforming a <style> tag to inline style. Useful to tranform Google Documents into Email-compatible format
const cssParser = require('css')
const { JSDOM } = require('jsdom')
function cssToInlineStyle (inputHtml) {
let style = inputHtml.match(/(?:<style[^>]*>)((?:[\r\n]|.)*?)(?:<\/style>)/)
const html = inputHtml.replace(/<style[^>]*>(([\r\n]|.)*?)<\/style>/, '')
if (!style) {
throw new Error('error while parsing')
}
style = style[1]
const { stylesheet } = cssParser.parse(style)
const { document } = (new JSDOM(html)).window
function setStyle (rule, element) {
rule.declarations.forEach(decl => {
element.style[decl.property] = decl.value
})
}
stylesheet.rules.forEach((rule, i) => {
rule.selectors.forEach(selector => {
const elements = document.querySelectorAll(selector)
if (!elements || !elements.length) {
return
}
elements.forEach(elem => setStyle(rule, elem))
})
})
return document.documentElement.outerHTML
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment