Created
June 28, 2020 15:36
-
-
Save sempostma/2762746e45dfc23c296d0f100fec89e4 to your computer and use it in GitHub Desktop.
Convert external styles to inline styles
This file contains 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
var proto = Element.prototype; | |
var slice = Function.call.bind(Array.prototype.slice); | |
var matches = Function.call.bind( | |
proto.matchesSelector || | |
proto.mozMatchesSelector || | |
proto.webkitMatchesSelector || | |
proto.msMatchesSelector || | |
proto.oMatchesSelector | |
); | |
// Returns true if a DOM Element matches a cssRule | |
var elementMatchCSSRule = function (element, cssRule) { | |
return matches(element, cssRule.selectorText); | |
}; | |
// Returns true if a property is defined in a cssRule | |
var propertyInCSSRule = function (prop, cssRule) { | |
return prop in cssRule.style && cssRule.style[prop] !== ""; | |
}; | |
// Here we get the cssRules across all the stylesheets in one array | |
var cssRules = slice(document.styleSheets).reduce(function (rules, styleSheet) { | |
return rules.concat(slice(styleSheet.cssRules)); | |
}, []); | |
var getAppliedCss = function (elm) { | |
// get only the css rules that matches that element | |
var elementRules = cssRules.filter(elementMatchCSSRule.bind(null, elm)); | |
var style = [] | |
if (elementRules.length) { | |
for (i = 0; i < elementRules.length; i++) { | |
for (var j = 0; j < elementRules[i].style.length; j++) { | |
var key = elementRules[i].style[j] | |
var value = elementRules[i].style[key] | |
style.push([key, value]) | |
} | |
} | |
} | |
if (elm.getAttribute("style")) { | |
for (var i = 0; i < elm.style.length; i++) { | |
var key = elm.style[i] | |
var value = elm.style[key] | |
style.push([key, value]) | |
} | |
} | |
return style; | |
}; | |
function getStylesObject(element) { | |
var style = getAppliedCss(element); | |
var styleObj = {} | |
for (var i = 0; i < style.length; i++) { | |
var element = style[i]; | |
styleObj[element[0]] = element[1] | |
} | |
return styleObj | |
} | |
function inlineStyles(element) { | |
Object.assign(element.style, getStylesObject(element)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment