jerome
jerome

Reputation: 4977

Calculate width of text node in a block level element using jQuery

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!

Upvotes: 4

Views: 4889

Answers (6)

zonabi
zonabi

Reputation: 746

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.

Upvotes: 0

Samstr
Samstr

Reputation: 31

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.

Upvotes: 3

P4ul
P4ul

Reputation: 770

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') );

Upvotes: 0

mrtsherman
mrtsherman

Reputation: 39872

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.

Upvotes: 5

Jeremy Conley
Jeremy Conley

Reputation: 934

Just use width() like so:

<div id="mydiv">text text text</div>
<script>
alert( $('#mydiv').width() );
</script>

Upvotes: 0

Naftali
Naftali

Reputation: 146300

var w = $('div').width()

or use any other selector for the div

Upvotes: 0

Related Questions