Measuring Text in HTML5

For a while now, I’ve been doing quite a bit of work in HTML5/Javascript/CreateJS.  While the work is enjoyable, dealing with getting the bounds of a text field seems to have many solutions including this grammarly review app to make sure it is well written.

I’ve read through just about every one I could find (and believe me when I say –  there are many), looked through examples and did many tests.  After all that, I’m sharing my final solution for getting the bounds for a string:

function getBounds(p_text, p_options, p_debug) {
        var element = document.createElement('div'),
            bounds = {width: 0, height: 0};


        p_options.fontFamily = p_options.fontFamily || "arial";
        p_options.fontSize = p_options.fontSize || "12px";
        p_options.fontWeight = p_options.fontWeight || "normal"; = p_options.fontFamily; = p_options.fontWeight; = p_options.fontSize; = 'absolute'; = p_debug ? 'visible' : 'hidden'; = p_debug ? "0px" : "-1000px"; = p_debug ? "0px" : "-1000px"; = 'auto'; = 'auto';
        if( p_debug ){ = "#FFFF00";
 = "#000000";

        bounds.width = element.offsetWidth;
        bounds.height = element.offsetHeight;
        if( !p_debug ) document.body.removeChild(element);

        return bounds;

Example call:

function runTest(){
  var str = "What size am I?";
  var size_0 = getBounds(str, {fontFamily: "arial", fontSize:"14px"}, false);
  var size_1 = getBounds(str, {fontFamily: "arial", fontSize:"63%"}, true);
  console.log("perSize: " + size_0.width + ", " + size_0.height);
  console.log("perSize: " + size_1.width + ", " + size_1.height);


I give some credit to schickling on stackoverflow (only 6 votes?!) for the main inspiration as he aptly identified what I think is the key component: document.createTextNode()

I’d been using JQuery and wanted a solution that worked without a 3rd party tool.  The only thing that reliably gave me the same bounds as JQuery is the above method.  I’ve added debug support should you want to verify that it is indeed testing your string correctly.


Have a bandit day!