javascriptjquerytextheight

How to get the real height of a text?


Referring to this example:

$(document).ready(function() {    
    var body = $('body'),
        text = $('#text');
    
    body.append('<br /><strong>jQuery</strong>');
    body.append('<p>Width: ' + text.width() + '</p>');
    body.append('<p>Height: ' + text.height() + '</p>');
    
    body.append('<br /><strong>getBoundingClientRect</strong>');
    body.append('<p>Width: ' + text[0].getBoundingClientRect().width + '</p>');
    body.append('<p>Height: ' + text[0].getBoundingClientRect().height + '</p>');
});
svg {
    border: 1px solid #3d3d3d;
}
<p>
    This example works as expected in Chrome 19, but not
    in Firefox 11 and Internet Explorer 9.
</p>

<br /><br />

<svg version="1.1" width="600" height="200">
    <text x="100" y="100" class="mediumText" id="text">jQuery rocks!</text>
</svg>

The result is the height of the box containing the text (the one you can see if you select the text with the mouse), which is higher then the real height of the text.
Is there a way to get the real height with jQuery or plain JS?
In the example I tried with

text.height()

and

text[0].getBoundingClientRect().height  

with no luck, it says 19px instead of 14px.


Solution

  • Get the computed font-size for your text element instead:

    parseInt(window.getComputedStyle(text[0]).fontSize, 10);
    

    font-size represents the size of an em square for a font. It should be noted that, while most glyphs will stay inside the bounds of an em square, some may exceed those bounds. This doesn't usually occur on the vertical dimentions, though.

    Give it a try: http://jsfiddle.net/uzgJX/1/. Tip: screenshot and copy into your favourite image editor, then select the pixels exactly to the height of the text and compare with the value given in the fiddle.