Skip to content

Instantly share code, notes, and snippets.

@andy-blum
Last active October 19, 2023 12:31
Show Gist options
  • Save andy-blum/648b8bd31bb3404237f85b8a30d543d0 to your computer and use it in GitHub Desktop.
Save andy-blum/648b8bd31bb3404237f85b8a30d543d0 to your computer and use it in GitHub Desktop.
Style Diff
const styleDiff = (elementOne, elementTwo) => {
const elOneStyles = window.getComputedStyle(elementOne);
const elTwoStyles = window.getComputedStyle(elementTwo);
const styleDiff = new Set();
for (const prop in elOneStyles) {
if (elOneStyles[prop] !== elTwoStyles[prop]) {
styleDiff.add(`${prop}: ${elOneStyles[prop]} | ${elTwoStyles[prop]}`);
}
}
for (const prop in elTwoStyles) {
if (elOneStyles[prop] !== elTwoStyles[prop]) {
styleDiff.add(`${prop}: ${elOneStyles[prop]} | ${elTwoStyles[prop]}`);
}
}
console.log(styleDiff);
}
/**
* Gets styles of an element for comparison on a different page.
*
* @param element element to get all the styles of
* @returns object version of getComputedStyles()
*/
const getStyles = (element) => {
const elementStyles = window.getComputedStyle(element);
const styleSet = new Map();
for (const prop in elementStyles) {
if (
!parseInt(prop) &&
!prop.startsWith('-webkit') &&
!prop.startsWith('Webkit') &&
!prop.startsWith('-moz') &&
!prop.startsWith('Moz') &&
!prop.startsWith('-ms')
) {
styleSet.set(prop, elementStyles[prop])
}
}
return Object.fromEntries(styleSet.entries());
}
/**
* Creates a set of style differences between an element on this page and a stylesObj from another page.
* @param element element to compare styles to
* @param stylesObj copied styles object from elsewhere
*/
const styleDiff = (element, stylesObj) => {
const elOneStyles = getStyles(element);
const styleDiff = new Set();
for (const prop in elOneStyles) {
if (elOneStyles[prop] !== stylesObj[prop]) {
styleDiff.add(`${prop}: ${elOneStyles[prop]} | ${stylesObj[prop]}`);
}
}
for (const prop in stylesObj) {
if (elOneStyles[prop] !== stylesObj[prop]) {
styleDiff.add(`${prop}: ${elOneStyles[prop]} | ${stylesObj[prop]}`);
}
}
console.log(styleDiff);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment