Get Computed Font-Family in JavaScript

How to get the actual rendered font when it's not defined in CSS?

I suggest this function:

function css( element, property ) {
return window.getComputedStyle( element, null ).getPropertyValue( property );
}

Usage:

css( object, 'font-size' ) // returns '16px' for instance

Note: getComputedStyle doesn't work in IE8.

Live demo: http://jsfiddle.net/4mxzE/

console.log(
getComputedStyle(document.getElementById('test'), null)
.getPropertyValue('font')
)
#test {
font-family: fantasy, cursive;
}
<div id="test">Lorem ipsum dolor sit font-face</div>

Get computed font size for DOM element in JS

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.

Use getComputedStyle to identify the CSS font-weight for all P tags

Use el.querySelectorAll() to get the nodeList, el.querySelector() will return the first node of the selector only. Then you just need to use getComputedStyle(selector).getPropertyValue('style') to get the computed style. From there is just concatenating the strings together and setting the innerHTML or textContent to the string.

Once you have the nodeList, run the elements through a loop to get each one.

let pTagClass = document.querySelectorAll('.check-weight')

function getFontWeight(els) {
els.forEach(weight => {
// weight now represents each individual node in
// our nodeList that was passed into the function
let compStyle = getComputedStyle(weight).getPropertyValue('font-weight');
let str = `<span class="bookmark">font-weight is: ${compStyle},</span>`
let currentText = weight.textContent
weight.innerHTML = `${str} ${currentText}`
})
}

getFontWeight(pTagClass)
.check-weight {
font-family: "Bahnschrift", sans-serif;
}

.heavy {
font-weight: bold;
}

.normal {
font-weight: normal;
}

.light {
font-weight: lighter;
}

.bookmark {
font-weight: normal;
font-size: smaller;
background-color: yellow;
padding: 2px;
}
<p class="heavy check-weight">This is a heavy weight</p>
<p class="heavy check-weight">This is also a heavy weight</p>
<p class="light check-weight">This is a light weight</p>
<p class="normal check-weight">This is normal</p>

How to get the rendered font in JavaScript?

It is still not possible to access this information from Web-APIs.

There is an ongoing discussion in the Houdini group about including a font-metrics API, that is supposed to include something like that, but it's still not even proposed as a spec draft and there will be a lot of burden on the road.

What font(s) are being used? This is complicated because multiple fonts can be used per paragraph, per line, per word, and even per glyph. The fonts should be exposed in the form of handles with complete font information, and (for web fonts) a handle to the raw font data. dbaron & eae are going to own this area and propose an API.

Indeed, one could have one font for the glyph ̂ (U+0302), and another one for the glyph a (U+0061) which would make the combined glyph would actually use two different fonts.

Current discussions seem to point to a Font interface available from document.measureElement and document.measureText methods. This interface would expose two properties: a DOMString name, and a number glyphsRendered.
However, once again these are still discussion and still not yet proposed as drafts, a lot of discussion is still to be made and I wouldn't hold my breath waiting for it to be implemented anywhere any time soon.


Now, there are hacks, like numerous other Q/A already told don't stick to the accepted answer there, implying looking at the size of the rendering for the simplest, and looking at the rendered pixels for the more advanced ones, but being hacks, they won't work in every cases.

For instance, I could have a custom font on my system that would render only some characters borrowed from a well-known font, no such hack would be able to tell if the browser did fallback to that font or the actual well-known one.

The only way to know for sure is to keep the control and use web-fonts.

How do I get the font style (font-family) from an element

You can use getComputedStyle() and getPropertyValue().

Here's a running example:

var test = document.getElementById("test");

var result = document.getElementById("result");

result.value = getComputedStyle(test).getPropertyValue("font-family");
#test {

font-family: "Trebuchet MS",sans-serif;

}
<span id="test">What font family am I?</span>

<input id="result"></input>

How do I determine which html elements are using a font?

Getting all elements grouped by computed font-family style

If you're interested in an extremely rudimentary solution, try this:

var fonts = {};

document.querySelectorAll('*').forEach(function(element) {
var fontFamily = window.getComputedStyle(element).getPropertyValue('font-family');

fonts[fontFamily] = fonts[fontFamily] || [];

fonts[fontFamily].push(element);
});

console.log(fonts);

It'll group the page's elements by computed font-family and then log them to the console.

At least on Chrome Dev Tools, hovering the logged element will highlight it in the page.

Note that "computed font-family" doesn't mean the element was actually rendered using that font-family, only that it's the font computed from the CSS (or lack thereof, in the case of default fonts).

Getting all elements whose computed font-family includes font X

Here's a similar approach, targeting a specific font:

function getElementsUsingFont(fontName) {

var elements = [];

document.querySelectorAll('*').forEach(function(element) {

var fontFamily = window.getComputedStyle(element).getPropertyValue('font-family');

if (fontFamily.includes(fontName)) {

elements.push(element);

}

});

return elements;

}

console.log(getElementsUsingFont('monospace'));
<span style="font-family: monospace">Dragons!</span>


Related Topics



Leave a reply



Submit