Home  >  Article  >  Web Front-end  >  How to Get the Actual Font Name Used by a DOM Element in JavaScript?

How to Get the Actual Font Name Used by a DOM Element in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 06:31:30493browse

How to Get the Actual Font Name Used by a DOM Element in JavaScript?

Getting the Computed Font-Family in JavaScript

In this follow-up to a previous question, we aim to provide a solution for obtaining the actual font name of a DOM element using JavaScript.

The generic "computed style" function returns the full font string defined for an element, including fallbacks. However, to match this against dropdown font family entries, we require a fixed font name for the actual font used.

Solution:

To retrieve the computed font-family, consider the following approach:

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

Notes:

  • This method only returns the primary font family specified for the element.
  • Some browsers (e.g., Chrome and Firefox) support the "font-family" property as defined in the CSS Font Interface Module Level 3. This interface provides more fine-grained control over the computed font-family.

Source:

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

The above is the detailed content of How to Get the Actual Font Name Used by a DOM Element 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