13

I want to know exact length in pixels of String i.e. "Hello World".

It should not be length of my container.

Any Help???

David
  • 8,340
  • 7
  • 49
  • 71
Kundan Atre
  • 3,853
  • 5
  • 26
  • 39
  • 1
    *"It should not be length of my container."* Pick the right container (e.g., a span with no padding) and there's no difference. – T.J. Crowder Feb 13 '13 at 11:53

3 Answers3

9

Put your text in a <span> and use JavaScript to measure the width of your <span>.

HTML:

<span id="text">Dummy text</span>

JavaScript:

var textWidth = document.getElementById("text").clientWidth;

jQuery:

$('#text').width();
Mike
  • 1,158
  • 5
  • 22
  • 32
  • This does not work if the `span` has a CSS style which sets its width to `100%` for example! – Andry Feb 04 '16 at 19:12
  • You're right @Andry. Except `span` is per definition an [inline element](https://developer.mozilla.org/en-US/docs/Web/HTML/Inline_elements). This means that you cannot define its width without changing its display to e.g. `block` or `inline-block`. – Mike Jul 22 '16 at 21:12
  • Also, another good answer mentioned here: https://stackoverflow.com/a/32558114/5864984. – Elnur Shabanov Apr 01 '20 at 05:22
5

You can create some inline element (span, for example), set your string as element's content (innerHTML), insert it into document (append to some element) and get it's width (clientWidth).

There is no other way to measure length of string in pixels because it depends on font style.

Artem Sobolev
  • 5,891
  • 1
  • 22
  • 40
-1

Since the pixel length of the string will change depending on independently applied CSS attributes such as font and weight and size, I can't see this being possible in JS.