Forum Moderators: not2easy

Message Too Old, No Replies

width

Getting the width of a class

         

Alternative Future

3:09 pm on Nov 9, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi all,

I have various html tags/elements such as:
<select name="test" class="selectStyle" id="test">
<input type="text" name="test2" id="test2" class="textStyle">

I am after these style width's using something like document.getElementById("test").style.width but nothing is displayed! Am I doing this wrong or is it not possible?

TIA,

-Gs

Robin_reala

3:45 pm on Nov 9, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You're trying to get the width that's directly set on an element (style=""), not the one that's set in a linked stylesheet. For that you'd need getComputedStyle. Unfortunately IE doesn't support this. A function that works with both (which I've blatently stolen from Quirksmode [quirksmode.org]) would be something like:

function getStyle(el,styleProp)
{
var x = document.getElementById(el);
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
return y;
}

createErrorMsg

3:48 pm on Nov 9, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Two thoughts:

1. Try using single quotes insead of double quotes.
2. Try explicitly setting a width property for those elements, even if it's value starts at "auto." I've had instances where javaScript was unable to alter a style property that didn't already have a value set in the CSS.

If neither of those help, I suggest posting to the JavaScript Forum [webmasterworld.com]. The experts there will certainly be able to get you straight.

cEM

johnl

10:58 pm on Nov 9, 2005 (gmt 0)

10+ Year Member



Hi,
Danny Goodman has written an instructive article about this (Cooking with JavaScript & DHTML, Part 5), which I would like to recommend herewith.
Good Luck!