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?
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?).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With