Calculate text width

by kontrach

HTML

<div id="fixed-width" style="width: 40px;">
  'empty'
</div>

CSS

#fixed-width{
  border: 1px solid red;
}

JavaScript

var div = document.querySelector('#fixed-width');

var oldWidth = div.getBoundingClientRect().width;
var oldDisplayValue = div.style.display || window.getComputedStyle(div).display;
console.log('old display', div.style.display, window.getComputedStyle(div).display);
div.style.display = 'inline';
div.style.width = "auto!important;";
div.textContent = 'super long string mmmm m m m m m m m m m';


var newWidth = div.getBoundingClientRect().width;
console.log(newWidth);

div.style.width = newWidth + 'px';
div.style.display = oldDisplayValue;