I'm trying to do something like:
$('<span>random text in here</span>').width()
But the width it's returning is 0. (The reason I'm trying to do this is to get the pixel width of a given text.)
How would I get this width, programmatically?
Thanks
Assigning the Width of the Span ElementYou can assign a width to the span after setting its “display” property to either “block” or “inline-block.” Moreover, you can use the float and width properties to assign a width to the same element. The width of span is affected by the default display property of the same.
Find the image file in your Finder, right click the image and select Get Info. A pop-up window will open with the dimensions of your image displaying in the More Info section. The dimensions show the pixel height and width of your photo.
getBoundingClientRect() method To get the width and height of the element you should use the corresponding property names. The width and height properties of the getBoundingClientRect() method will return the value based on the CSS box-sizing property of the element.
The clientWidth property is used to get the width of its element. This value will represent the width of text in pixels.
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 :
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With