0

If I have some HTML

<div id="container">
  <div class="foo" style="width:75%;">Bar!</div>
</div>

and if I write this JavaScript (assuming jQuery for the benefit of the question)

alert( $("#container .foo")[0].style.width );

it should alert "75%". Will this output be consistent in every "modern" browsers? If not, what are the most popular non-standard browsers (even IE) that will fail to return the correct value?

** Edit **

PLEASE! There are only two statements with question marks... THOSE are the questions!

Now, let me add something that may help not mislead the answers...

  1. I know element.style is available across all browsers.
  2. I know element.style.width is also available.
  3. Using jQuery 1.3.2, calling $("#container .foo").css('width') does return "75%" which is not true since at least version 1.6.4 (we're even beyond that major release too); the most recent jQuery version always output the width in pixels now.

So, considering the given HTML, will getting the element's style.width always return the true, declared size (ie. in percentage) across all browsers, or is there any rogue, non-standard one that will return a computed width in pixels?

Community
  • 1
  • 1
Yanick Rochon
  • 51,409
  • 25
  • 133
  • 214

1 Answers1

2

Yes it is supported in all major browsers. As seem here with some notes for old IE versions.

Here you can found all available properties in this version of the DOM API.

EDIT

About the consistence of the value returned across browsers... that's depends on you, since it returns only what's attributed via this API: if you use %, you'll get %; if you use em you'll get em and so on.

It couldn't make sense by other way. Let's say that you apply a 70% width in your element and, hypothetically, the engine uses only pixel values under the hood. So it will convert the value internally to 70% of the pixels count of the parent's width. Once your parent's width is changed the value stored in pixels gone forever, it will be evaluated in another percentage value.

tl;dr - It only makes sense to be stored as is, so what you give is what you get.

I'm pretty sure about this behavior. But just to make sure, I confirmed this behavior on earlier versions of Chrome, Firefox, Opera and IE 8+. So, remain in peace buddy and enjoy this feature.

cvsguimaraes
  • 12,910
  • 9
  • 49
  • 73