Kunal Vashist
Kunal Vashist

Reputation: 2471

How to calculate width of text using javascript?

How to get the width of the text.

var e=document.createElement('span');
          e.style.fontSize = scope.fontsize;
          e.innerHTML = "test";
          console.log(e.offsetWidth);

Width always comes as 0

Upvotes: 2

Views: 73

Answers (1)

jHilscher
jHilscher

Reputation: 1868

It seems like you have to append the created element to the document.

var e=document.createElement('span');
document.body.appendChild(e);
e.style.fontSize = 14;
e.innerHTML = "test";
console.log(e.offsetWidth);
e.remove();

Output: 23


Hiding the element does not work ether.

 e.style.display= "none";

Output: 0


To "hide it" you could add a CSS like that. But with the added remove() it will likely not show up anyway. But adding position:absolute; is a good idea, since this will prevent flickering of the rest of the html content.

   position:absolute;
   margin-left:-1000em;

Upvotes: 2

Related Questions