Skip to content

Instantly share code, notes, and snippets.

@justinribeiro
Created October 18, 2019 15:43
Show Gist options
  • Save justinribeiro/c4d39824ee6374fe7c8e9b5a4d43defa to your computer and use it in GitHub Desktop.
Save justinribeiro/c4d39824ee6374fe7c8e9b5a4d43defa to your computer and use it in GitHub Desktop.
Find font definitions of elements in a page.

Find font defintions for elements within a page with DevTools

This is simple DevTools snippt that uses TreeWalker to find textNodes, and then we parse what font styles are in use on that node with getComputedStyle.

Note, this won't travel the ShadowDOM which is it's own can of worms.

function findTextNodesFor(element){
  let node; 
  const discoveredTextNodes = []; 
  const walkTree = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, null, false);
  while(node = walkTree.nextNode()) {
    discoveredTextNodes.push(node);
  }
  return discoveredTextNodes;
}

weights = {
  100: "Thin",
  200: "Extra Light",
  300: "Light",
  400: "Regular",
  500: "Medium",
  600: "Semibold",
  700: "Bold",
  800: "Extra Bold",
  900: "Black"
};

fonts = new Set();

findTextNodesFor(document.querySelector('body'))
  .filter(node => !['SCRIPT', 'STYLE', 'NOSCRIPT'].includes(node.parentNode.nodeName))
  .forEach(node => {
  const computedStyle = window.getComputedStyle(node.parentNode);
  const font = computedStyle.fontFamily || "";
  const size = computedStyle.fontSize;
  const weight = computedStyle.fontWeight;
  const weights = {
    100: "Thin",
    200: "Extra Light",
    300: "Light",
    400: "Regular",
    500: "Medium",
    600: "Semibold",
    700: "Bold",
    800: "Extra Bold",
    900: "Black"
  };

  fonts.add(`${size} ${weights[weight]} ${font}`);
});

console.table([...fonts].sort());

Example output

image

Why?

Co-worker sent me a link to this and I decided to rewrite it into report form.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment