Text Bounds!

Get text bounds with pure JS

HTML

<script src="https://code.jquery.com/jquery-2.2.2.min.js&quot;"></script>

CSS

body {
  overflow:visible;
  background:transparent;
  font-size:66px;
}

JavaScript

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

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

        element.appendChild(document.createTextNode(p_text));

        p_options.fontFamily = p_options.fontFamily || "arial";
        p_options.fontSize = p_options.fontSize || "12px";
        p_options.fontWeight = p_options.fontWeight || "normal";

        element.style.fontFamily = p_options.fontFamily;
        element.style.fontWeight = p_options.fontWeight;
        element.style.fontSize = p_options.fontSize;
        element.style.position = 'absolute';
        element.style.visibility = p_debug ? 'visible' : 'hidden';
        element.style.left = p_debug ? "0px" : "-1000px";
        element.style.top = p_debug ? "0px" : "-1000px";
        element.style.width = 'auto';
        element.style.height = 'auto';
        
        if( p_debug ){
        	element.style.background = "#FFFF00";
          element.style.color = "#000000";
        }

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

        return bounds;
}

runTest();