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
Release: 2024-11-26 14:30:10
Original
336 people have browsed it

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'];
}
Copy after login

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');
}
Copy after login

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'];
}
Copy after login

This function can be used as follows:

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

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template