Home >Web Front-end >CSS Tutorial >How Can I Reliably Get an HTML Element's Font Size?

How Can I Reliably Get an HTML Element's Font Size?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-30 21:56:09126browse

How Can I Reliably Get an HTML Element's Font Size?

Determining Font Size in HTML

When attempting to retrieve the font size of an element, the initial idea of accessing style.fontSize might prove insufficient. This is particularly true when the font size is defined externally in a stylesheet, resulting in an empty string when retrieved using this method.

To address this, you can utilize window.getComputedStyle, as illustrated below:

var el = document.getElementById('foo');
var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style); // Convert the style value to a numeric font size
el.style.fontSize = (fontSize + 1) + 'px'; // Increment the font size by 1

This approach accurately retrieves the font size, even if it's defined in a stylesheet. The resulting fontSize variable can then be used to dynamically adjust the font size of the specified element.

The above is the detailed content of How Can I Reliably Get an HTML Element's Font Size?. 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