4

Say I have:

<div>Some variable amount of text.</div>

How can I get the width (in pixels) of the text in the div?

Keep in mind that the amount of text will vary unpredictably from div to div.

Thanks!

jerome
  • 4,809
  • 13
  • 53
  • 70
  • what effect are you trying to achieve that would require knowing width in pixels? many times, these situations have a solution that does not require actual pixel values... – Hersheezy Mar 15 '11 at 22:22

6 Answers6

5

Sounds like you want the width of the contents, not of the div itself as others have provided. I think that you will need to wrap your contents in a span so that you can then measure the width of the span. The div will always be as wide as possible. You need something that collapses to the size of the content that you can measure instead.

mrtsherman
  • 39,342
  • 23
  • 87
  • 111
  • Thank you @mrtsherman, that is the direction that I am beginning to think I need to go, as well. – jerome Mar 16 '11 at 00:26
3

The best way I found is to use CSS rule "display:inline;" to bound only textNode of given HTML Element, then use offsetWidth JS method.

<div style="display:inline;" id="gotWidthInPixels" >Some variable amount of text.</div>
<script>
  //either:
  var widthInPixels= $('#gotWidthInPixels')[0].offsetWidth; 
  //or
  var widthInPixels= document.getElementById("gotWidthInPixels").offsetWidth;
</script>

This will give you exact width in pixels of any HTML Element.

mrjimoy_05
  • 3,452
  • 9
  • 58
  • 95
Samstr
  • 31
  • 3
0

i had some weird issues where whitespace spaces where breaking the width calculation in jquery. not sure exactly why, if it was because of string variables and concatenation, or the JMVC framework, or just jQuery.

But, making the spaces non-breaking spaces

&nbsp;

seemed to solve it. just throwing that out there in case it helps.

zonabi
  • 746
  • 6
  • 20
0
var w = $('div').width()

or use any other selector for the div

Naftali
  • 144,921
  • 39
  • 244
  • 303
0

Just use width() like so:

<div id="mydiv">text text text</div>
<script>
alert( $('#mydiv').width() );
</script>
Jeremy Conley
  • 924
  • 5
  • 6
0

with regards to @mrtsherman if you want the width of just the text you could use

var myDiv = $('#myDiv'); 

//div width
var textWidth = sb.width();

//remove padding and margin from left and right
textWidth -= parseInt(sb.css('padding-left') ) + parseInt(sb.css('margin-left') );
textWidth -= parseInt(sb.css('padding-right') ) + parseInt(sb.css('margin-right') );
P4ul
  • 770
  • 5
  • 15