Home >Web Front-end >CSS Tutorial >How to Get a DOM Element\'s Computed Font Size in JavaScript?

How to Get a DOM Element\'s Computed Font Size in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-26 14:30:10297browse

How to Get a DOM Element's Computed Font Size in JavaScript?

Getting Computed Font Size of a DOM Element in JavaScript

Understanding the computed font-size of a DOM element is crucial, especially when manipulating elements with complex style inheritance. Here's how you can retrieve this information:

If you have access to Internet Explorer's non-standard element.currentStyle property, you can use this simple code:

if (el.currentStyle) {
  return el.currentStyle['fontSize'];
}

For other browsers that support the DOM Level 2 standard, you can utilize the getComputedStyle method:

if (document.defaultView && document.defaultView.getComputedStyle) {
  return document.defaultView.getComputedStyle(el, null).getPropertyValue('font-size');
}

As a fallback, if neither currentStyle nor getComputedStyle are available, you can still access the inline CSS property using element.style:

else {
  return el.style['fontSize'];
}

This function can be used as follows:

var element = document.getElementById('elementId');
var fontSize = getStyle(element, 'font-size');

The above is the detailed content of How to Get a DOM Element\'s Computed Font Size 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