Home  >  Article  >  Web Front-end  >  How to Get the True Font Family Name in JavaScript?

How to Get the True Font Family Name in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 06:27:30665browse

How to Get the True Font Family Name in JavaScript?

Get the True Font Family Value in JavaScript

In a previous question, it was discussed how to obtain the font size through JavaScript. Now, we'll explore how to determine the actual font family name from the computed style of a DOM element.

By default, the computed style function only returns the entire font definition, including the full font family stack. However, for selecting fonts in a drop-down menu, we need the exact name of the font in use.

Solution

To extract the true font family name, utilize the following code:

let para = document.querySelector('p');
let compStyles = window.getComputedStyle(para);
let computedFontFamily = compStyles.getPropertyValue('font-family');

This will return a string like "Times New Roman", which can be matched against the options in your font family drop-down.

Browser Support

The code above is supported in all major browsers, providing a consistent way to get the computed font family value.

The above is the detailed content of How to Get the True Font Family Name in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn