Obtaining Computed Font Size in DOM Elements Using JavaScript
Determining the actual font size applied to a DOM element, considering inherited and global settings, can be a common task in web development. This is especially useful when working with plugins or automating tasks that require accurate font size information.
Generic Approach for Computed Font Size Detection
To achieve framework-independent font size retrieval, you can leverage the following approach:
function getStyle(el, styleProp) { // Convert property name to camelCase for IE compatibility let camelize = (str) => str.replace(/\-(\w)/g, s => s[1].toUpperCase()); // Attempt IE's non-standard currentStyle if (el.currentStyle) { return el.currentStyle[camelize(styleProp)]; } // Try DOM Level 2 getComputedStyle if available else if (document.defaultView && document.defaultView.getComputedStyle) { return document.defaultView.getComputedStyle(el, null).getPropertyValue(styleProp); } // Fallback to inline style else { return el.style[camelize(styleProp)]; } }
Usage:
const element = document.getElementById('elementId'); const fontSize = getStyle(element, 'font-size');
By using this approach, you can obtain the computed font size for any DOM element, regardless of its inheritance or global settings.
The above is the detailed content of How Can I Get the Computed Font Size of a DOM Element in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!