Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine which html elements are using a font?

I'm working on a website that downloads about a dozen fonts and I'm trying to figure out where they're being used. I know that the page will only download a font once it's being applied to actual rendered text - I just can't tell where that text is on the page. Does anyone know any methods or tools for figuring out where a font is being applied on a large web page?

Chrome dev tools were helpful in tracking down the fonts being downloaded by the page - but how do I track down which elements are using these fonts?

like image 455
Andrew Kirchmyer Avatar asked Jun 05 '26 12:06

Andrew Kirchmyer


1 Answers

Getting all elements grouped by computed font-family style

If you're interested in an extremely rudimentary solution, try this:

var fonts = {};

document.querySelectorAll('*').forEach(function(element) {
    var fontFamily = window.getComputedStyle(element).getPropertyValue('font-family');

    fonts[fontFamily] = fonts[fontFamily] || [];

    fonts[fontFamily].push(element);
});

console.log(fonts);

It'll group the page's elements by computed font-family and then log them to the console.

At least on Chrome Dev Tools, hovering the logged element will highlight it in the page.

Note that "computed font-family" doesn't mean the element was actually rendered using that font-family, only that it's the font computed from the CSS (or lack thereof, in the case of default fonts).

Getting all elements whose computed font-family includes font X

Here's a similar approach, targeting a specific font:

function getElementsUsingFont(fontName) {
  var elements = [];

  document.querySelectorAll('*').forEach(function(element) {
    var fontFamily = window.getComputedStyle(element).getPropertyValue('font-family');

    if (fontFamily.includes(fontName)) {
      elements.push(element);
    }
  });

  return elements;
}

console.log(getElementsUsingFont('monospace'));
<span style="font-family: monospace">Dragons!</span>

Unfortunately, this will capture elements that include the given font name anywhere in its list of possible fonts. For example"

span {
     font-family: "Times New Roman", Georgia, ChuckNorris, monospace, 'Comic Sans';
}

The above snippet would capture any element with that style because "monospace" is in the list. You could tinker with the conditions to push the element to try to choose more carefully (regex maybe?).

like image 130
crenshaw-dev Avatar answered Jun 07 '26 20:06

crenshaw-dev