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!