Search code examples
javascripthtmlgetboundingclientrect

How can I get text dimensions?


This snippet gives the width of the "theDiv", which equals to the width of the page:

<div id="theDiv">This is some text</div>
<script>
    var rect = document.getElementById("theDiv").getBoundingClientRect();
    alert("width of text is (not): " + rect.width);
</script>

Is there any way to get the width (and height) of the actual text in the div?

note: I'm developing a chrome extension that analyzes web-pages - I cannot change the dom and the css, meaning I cannot use span instead of div or change the style of the element.


Solution

  • You can use a Range to measure text. For example:

    var range = document.createRange();
    range.selectNodeContents(document.getElementById("theDiv"));
    var rect = range.getBoundingClientRect();
    document.getElementById("out").innerHTML = "width of text is: " + rect.width;
    <div id="theDiv">This is some text</div>
    <div id="out"></div>