2

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.

nagy.zsolt.hun
  • 6,292
  • 12
  • 56
  • 95

4 Answers4

0

If you can't change the dom then you could make theDiv inline-block via CSS:

#theDiv {
   display: inline-block
} 

Ok, in this case you could create virtual element, append it to the dom, calculate dimensions and then remove it from dom:

// fetch source element and his content
var div = document.getElementById("theDiv"),
    text = div.innerHTML;

// create virtual span to calculate dimestions
var span = document.body.appendChild(document.createElement('span'));
    span.innerHTML = text,
    rect = span.getBoundingClientRect();

alert(rect.width);

// remove virtual span from the DOM
document.body.removeChild(span);
0

Getting an element's text's width by itself isn't possible without the use of an extra (inline, usually invisible) element, as far as I know, or could tell.
For those others who arrive here without OP's restrictions though, it is possible using only JS and without affecting the page's flow at all.

var target = ... // Whichever element's text's width you wish to measure
var ruler = document.createElement("span");

ruler.style.position = "absolute"; // remove from the page's flow
ruler.style.visibility = "hidden"; // and totally stop it from being rendered

// copy font-size, font-family and the text itself
ruler.style.fontSize = target.style.fontSize;
ruler.style.fontFamily = target.style.fontFamily;
ruler.innerHTML = target.innerHTML;

// add to the document so that the styles get applied, allowing us to discover its width
document.body.appendChild(ruler);
var textWidth = ruler.offsetWidth;
// and then promptly remove again from the document
document.body.removeChild(ruler);
chossenger
  • 613
  • 6
  • 15
0

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>
gilly3
  • 87,962
  • 25
  • 144
  • 176
0

You can use clientWidth or offsetWidth

Use var offsetWidth =element.offsetWidth; 

the difference is offsetWidth includes border width, clientWidth does not

enter image description here

vijay kani
  • 140
  • 8