Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get computed font size for DOM element in JS

Is it possible to detect the computed font-size of a DOM element, taking into consideration generic settings made elsewhere (In the body tag for example), inherited values, and so on?

A framework-independent approach would be nice, as I'm working on a script that should work standalone, but that is not a requirement of course.

Background: I'm trying to tweak CKEditor's font selector plugin (source here) so that it always shows the font size of the current cursor position (as opposed to only when within a span that has an explicit font-size set, which is the current behaviour).

like image 283
Pekka Avatar asked Dec 23 '09 20:12

Pekka


People also ask

How do you find an element's computed style?

getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain. Individual CSS property values are accessed through APIs provided by the object, or by indexing with CSS property names.

How do you set a computed style?

To set or copy JavaScript computed style from one element to another, we can loop through each style and call the setProperty method to set the styles on the target element. to add a div and a section element. We define the copyNode function that takes the sourceNode and targetNode .


Video Answer


1 Answers

You could try to use the non-standard IE element.currentStyle property, otherwise you can look for the DOM Level 2 standard getComputedStyle method if available :

function getStyle(el,styleProp) {   var camelize = function (str) {     return str.replace(/\-(\w)/g, function(str, letter){       return letter.toUpperCase();     });   };    if (el.currentStyle) {     return el.currentStyle[camelize(styleProp)];   } else if (document.defaultView && document.defaultView.getComputedStyle) {     return document.defaultView.getComputedStyle(el,null)                                .getPropertyValue(styleProp);   } else {     return el.style[camelize(styleProp)];    } } 

Usage:

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

More info:

  • Get Styles (QuirksMode)

Edit: Thanks to @Crescent Fresh, @kangax and @Pekka for the comments.

Changes:

  • Added camelize function, since properties containing hypens, like font-size, must be accessed as camelCase (eg.: fontSize) on the currentStyle IE object.
  • Checking the existence of document.defaultView before accessing getComputedStyle.
  • Added last case, when el.currentStyle and getComputedStyle are not available, get the inline CSS property via element.style.
like image 86
Christian C. Salvadó Avatar answered Oct 01 '22 22:10

Christian C. Salvadó