Get text width

S

Showtime

Hi! I have a text and I need to get its width in pixels. The font size is
not fixed. I've been suggested to put the text inside of an invisible div
and get the div's width. But I would need to force the div to shrink to fit
the text. Any idea?

Thanks in advance
 
S

Showtime

I answer my own question: it's better to use a span element.

function getElementWidth(Elem) {
if(document.getElementById) {
var elem = document.getElementById(Elem);
} else if (document.all){
var elem = document.all[Elem];
}
xPos = elem.offsetWidth;
return xPos;
}

<span id="test">asdfasdf</span>

alert(getElementWidth(test)) -> gets the span width
 
F

Fred Oz

Showtime said:
I answer my own question: it's better to use a span element.

function getElementWidth(Elem) {
if(document.getElementById) {
var elem = document.getElementById(Elem);
} else if (document.all){
var elem = document.all[Elem];
}
xPos = elem.offsetWidth;
return xPos;
}

<span id="test">asdfasdf</span>

alert(getElementWidth(test)) -> gets the span width

As a test case, why not:

<span onclick="alert(this.offsetWidth);">------</span>


For more information viewport features & issues, have a look
here:

<URL:http://www.quirksmode.org/viewport/compatibility.html>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top