Home  >  Article  >  Web Front-end  >  How to Retrieve the Computed Font-Family Value Using JavaScript?

How to Retrieve the Computed Font-Family Value Using JavaScript?

DDD
DDDOriginal
2024-10-24 06:51:01678browse

How to Retrieve the Computed Font-Family Value Using JavaScript?

Retrieving Computed Font-Family using JavaScript

This article delves into an extension of a previous inquiry, exploring how to obtain the actual font name of a DOM element, excluding any fallbacks. While the generic "computed style" method retrieves the complete font string, including fallbacks, our aim is to isolate the specific font used by the element.

To achieve this, we leverage the getComputedStyle() method provided by modern browsers. The following code snippet illustrates the 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>

In the example above, para represents the target paragraph element. The getComputedStyle() method returns a CSSStyleDeclaration object (compStyles) containing the computed styles of the element. To retrieve the computed font-family, use the getPropertyValue('font-family') method, which returns a string containing the actual font name, excluding any fallbacks.

This approach is supported by most major browsers, including Chrome, Firefox, Safari, and Edge. Refer to the Mozilla Developer Network documentation for further details: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle.

The above is the detailed content of How to Retrieve the Computed Font-Family Value Using 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