Get computed font-family in JavaScript

10.1k views Asked by At

This is a followup to this question.

I am working on a component for the CKEditor, a tweaked version of the font drop-down menus that always display the currently selected font family / size values, no matter where they were defined, using computedStyle and consorts.

As you can see in the other question, determining the font size works cross-browser now. Now I am having trouble working with the fontFamily attribute. My generic "computed style" function returns only the full font string that was defined, e.g.

Times New Roman, Georgia, Serif

What I need, in order to match the setting against the entries in the font family dropdown, is a fixed font name of the actual font of the DOM element I am checking.

Can this be done somehow, at least for the most common web fonts?

2

There are 2 answers

1
Azeem.Butt On

The UA picks the first font in the list that it finds installed. The fonts installed on the OS are not really a part of the DOM, so the best you can do is guess.

3
Augusto On

Here goes a way to get the computed font-family with JavaScript from the DOM:

let para = document.querySelector('p');
let compStyles = window.getComputedStyle(para);
let computedFontFamily = compStyles.getPropertyValue('font-family') // e.g. "Times New Roman"

Source: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle