15

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?

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088

2 Answers2

6

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
Augusto
  • 61
  • 1
  • 1
  • 1
    This will return something like this: `Segoe UI, Helvetica Neue, Helvetica, sans-serif`. Is there anyway to limit the return to just `Segou UI` (the first font)? – rudtek Jan 06 '22 at 17:55
  • 2023 checkup: is there a way to get the name of the font actually being **loaded and rendered**? – aetonsi Aug 08 '23 at 09:07
  • 1
    @rudtek if you need just the first in the list, you can simply split the string on commas. if you need the actual font loaded (`segoe ui` does not exist on non-windows devices), i think it's still not possible.... – aetonsi Aug 08 '23 at 09:09
3

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.

Azeem.Butt
  • 5,855
  • 1
  • 26
  • 22
  • You're right. Paul D. Waite presents a workaround that I'm not going to use in this case, but makes it possible to sort it out. – Pekka Dec 25 '09 at 17:54