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

How to Get the True Font Family Name in JavaScript?

Mary-Kate Olsen
Release: 2024-10-24 06:27:30
Original
737 people have browsed it

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');
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template