You have to have it rendered.
You may do this :
var s = $('<span>random text in here</span>');
s.appendTo(document.body);
var w = s.width();
s.remove();
Demonstration
Note that :
- nothing is displayed if you do this like I do in one go. For all practical purposes, nothing is inserted in the DOM,
- you could also use an in memory canvas but it wouldn't handle anything more complex than simple text and wouldn't take into account your span's css settings.
Here's the solution measuring the width of some text using an in memory canvas :
var canvas = document.createElement('canvas');
var c = canvas.getContext('2d');
// set here c.font to adjust it to your need
var w = c.measureText('random text in here').width;
Demonstration
I would use the first one in the general case but it might depend on why you want to measure the text.