A technique that works is to look at the computed style of the element. This is supported in Opera and Firefox (and I recon in safari, but haven't tested). IE (7 at least), provides a method to get a style, but it seems to be whatever was in the stylesheet, not the computed style. More details on quirksmode: http://www.quirksmode.org/dom/getstyles.html
Here's a simple function to grab the font used in an element:
/**
* Get the font used for a given element
* @argument {HTMLElement} the element to check font for
* @returns {string} The name of the used font or null if font could not be detected
*/
function getFontForElement(ele) {
if (ele.currentStyle) { // sort of, but not really, works in IE
return ele.currentStyle["fontFamily"];
} else if (document.defaultView) { // works in Opera and FF
return document.defaultView.getComputedStyle(ele,null).getPropertyValue("font-family");
} else {
return null;
}
}
If the CSS rule for this was:
#fonttester {
font-family: sans-serif, arial, helvetica;
}
Then it should return helvetica if that is installed, if not, arial, and lastly, the name of the system default sans-serif font. Note that the ordering of fonts in your CSS declaration is significant.
An interesting hack you could also try is to create lots of hidden elements with lots of different fonts to try to detect which fonts are installed on a machine. I'm sure someone could make a nifty font statistics gathering page with this technique.