-
-
Save ahoendgen/ebcabb595cc8465e4688275311a5c009 to your computer and use it in GitHub Desktop.
JS - List unique font information of all DOM elements
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
/** | |
* List unique font information of all DOM elements | |
* Based on the awesome code from AndrewRMinion | |
* @see {@link https://gist.github.com/macbookandrew/f33dbbc0aa582d0515919dc5fb95c00a URL of the base code} | |
* | |
* @see {@link https://gist.github.com/ahoendgen/ebcabb595cc8465e4688275311a5c009/ URL for this file} | |
* | |
* @author AndrewRMinion Design (https://andrewrminion.com) | |
* @author André Hoendgen (https://andre-hoendgen.de) | |
* @version 1.1 | |
* | |
* @license MIT | |
* @copyright AndrewRMinion Design | |
* | |
* @example Show all unique font stacks in use on the current page | |
* console.table(fontsInPage()); | |
*/ | |
function fontsInPage() { | |
// polyfill getComputedStyle | |
if (typeof getComputedStyle == 'undefined') { | |
getComputedStyle = function(elem) { | |
return elem.currentStyle; | |
}; | |
} | |
// set vars | |
var family, | |
weight, | |
style, | |
key, | |
thisNode, | |
allStyles = {}, | |
nodes = document.body.getElementsByTagName('*'); | |
// loop over all elements | |
for (var i = 0; i < nodes.length; i++) { | |
thisNode = nodes[i]; | |
if (thisNode.style) { | |
family = thisNode.style.fontFamily || getComputedStyle(thisNode, '')['fontFamily']; | |
weight = thisNode.style.fontWeight || getComputedStyle(thisNode, '')['fontWeight']; | |
style = thisNode.style.fontStyle || getComputedStyle(thisNode, '')['fontStyle']; | |
if(family === undefined) { | |
continue; | |
} | |
key = family + weight + style; | |
// get element’s style | |
if (allStyles[key] === undefined) { | |
allStyles[key] = { | |
family, | |
weight, | |
style, | |
}; | |
} | |
// get element:before’s style | |
family = getComputedStyle(thisNode, ':before')['fontFamily']; | |
weight = getComputedStyle(thisNode, ':before')['fontWeight']; | |
style = getComputedStyle(thisNode, ':before')['fontStyle']; | |
if (allStyles[key] === undefined) { | |
allStyles[key] = { | |
family, | |
weight, | |
style, | |
}; | |
} | |
// get element:after’s style | |
family = getComputedStyle(thisNode, ':after')['fontFamily']; | |
weight = getComputedStyle(thisNode, ':after')['fontWeight']; | |
style = getComputedStyle(thisNode, ':after')['fontStyle']; | |
if (allStyles[key] === undefined) { | |
allStyles[key] = { | |
family, | |
weight, | |
style, | |
}; | |
} | |
} | |
} | |
return allStyles; | |
} | |
// console.table(fontsInPage()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment