Reputation: 2471
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
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