By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,610 Members | 1,923 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,610 IT Pros & Developers. It's quick & easy.

Get text width

P: n/a
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
Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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
"Showtime" <di***************@usuarios.retecal.es> escribió en el mensaje
news:37*************@individual.net...
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

Jul 23 '05 #2

P: n/a
Showtime wrote:
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>

--
Fred
Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.