Created
November 26, 2016 03:06
-
-
Save matt-curtis/c2f7e9381b4cc9cabafd7ec73e758aff to your computer and use it in GitHub Desktop.
Get an element's unique (non-default) styling
This file contains hidden or 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 getDefaultStyling = function(tagName){ | |
if(!tagName) tagName = "dummy-tag-name"; | |
// Create dummy iframe | |
var iframe = document.createElement("iframe"); | |
document.body.appendChild(iframe); | |
// Create element within the iframe's document | |
var iframeDocument = iframe.contentDocument; | |
var targetElement = iframeDocument.createElement(tagName); | |
iframeDocument.body.appendChild(targetElement); | |
// Grab styling (CSSStyleDeclaration is live, and all values become "" after element removal) | |
var styling = iframe.contentWindow.getComputedStyle(targetElement); | |
var clonedStyling = {}; | |
for(var i = 0, len = styling.length; i < len; i++){ | |
var property = styling[i]; | |
clonedStyling[i] = property; | |
clonedStyling[property] = styling[property]; | |
} | |
// Remove iframe | |
document.body.removeChild(iframe); | |
// Return cloned styling | |
return clonedStyling; | |
}; | |
var getUniqueUserStyling = function(element){ | |
var allStyling = window.getComputedStyle(element); | |
var defaultStyling = getDefaultStyling(element.tagName); | |
var userStyling = {}; | |
for(var i = 0, len = allStyling.length; i < len; i++){ | |
var property = allStyling[i]; | |
var value = allStyling[property]; | |
var defaultValue = defaultStyling[property]; | |
if(value != defaultValue){ | |
userStyling[property] = value; | |
} | |
} | |
return userStyling; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment