0

Suppose I have a table in a web page:

<table><th id='th1'></th></table>

Then I define the CSS in the header:

#th1
{width: 100%;}

The question is, how to get the CSS width using JavaScript? I tried width, style.width, and jQuery("#th1").css("width"), but neither of them give me the result of '100%'.

3
  • I included the html for the table but it doesn't show up, it's just a simple table, with th tag, id='th1'... Commented Nov 19, 2009 at 17:18
  • @Estelle, when writing the post you can either surround code examples with the a backtick either side, or indent the code by four spaces; both will cause the code to be displayed/rendered as code. You can also select the text with your mouse/keyboard and then click on the button with the 1s and 0s on it to do the same. Commented Nov 19, 2009 at 17:21
  • thanks. it's funny, I just want to say thanks but when I click Add Comment it tells me I need at least 15 characters -:) Commented Nov 19, 2009 at 17:30

3 Answers 3

2

I think there's no way to get the percentage value you specified in your CSS file for your element width.

A solution would be to calculate it like this :

HTML:

<h1 id="header">Hello, World</h1>

Javascript (jQuery):

var percentageWidth = (($("#header").width()*100)/$("#header").parent().width())+"px";
Sign up to request clarification or add additional context in comments.

Comments

1

Just in case, if you want to get the actual current width in pixels, not what the CSS width says, you can do:

$('#th1').width();

Comments

1
<h1 id="myHeader">Text</h1>

$('#myHeader').css('width');

Should work every time.

1 Comment

the problem is, in above sample, it returns px instead of 100%

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.