Last active
October 19, 2023 12:31
-
-
Save andy-blum/648b8bd31bb3404237f85b8a30d543d0 to your computer and use it in GitHub Desktop.
Style Diff
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
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); | |
} |
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
/** | |
* 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