12

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

It should not be length of my container.

Any Help???

1
  • 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. Commented Feb 13, 2013 at 11:53

3 Answers 3

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();
Sign up to request clarification or add additional context in comments.

3 Comments

This does not work if the span has a CSS style which sets its width to 100% for example!
You're right @Andry. Except span is per definition an inline element. This means that you cannot define its width without changing its display to e.g. block or inline-block.
Also, another good answer mentioned here: stackoverflow.com/a/32558114/5864984.
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.

Comments

-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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.