2

I know this sounds simple, but here's what i got that's not working.

<style type="text/css">#graphelement{width:800px;height:300px;}</style>
<div id="graphlabel2">Right Axis Label</div>
<div id="graphelement"></div>

<script type="text/javascript">
var graphwidth = document.getElementById('graphelement').style.width;
document.getElementById('graphlabel2').style.width = graphwidth;
</script>

My problem is that 'graphwidth' always comes up empty. If i just grab the element's width (element.width), i get 'undefined' in 'graphwidth. All code above is within the body tag, even the initial style tag.

This is part of a larger script, but i can figure the rest out if i can get a width from and element and set it to another. My overall goal: i have an element whose width is set in inline styles. If the page is viewed on a handheld (i.e., screen width is smaller than graphwidth), then i want to set the width of the element and associated elements to screen.width. I seem to be having trouble retrieving and setting element.style.width though.

TPerry
  • 21
  • 1
  • 2
  • i think you can do what you want to achieve with media queries instead of JS – Huangism May 17 '12 at 20:26
  • @aurel he set the width in the css, maybe if you put the css in the header. but usually when it is undefined it means the element has not loaded on the page. however in his example the js is below the element – Huangism May 17 '12 at 20:32
  • I tried using inline stype
    and it does work - but you dont want that really
    – aurel May 17 '12 at 20:36

4 Answers4

4

style.width on an element is empty unless you assign it via javascript. Instead, what you want is computedStyle. Here is the some documentation.

window.getComputedStyle(document.getElementById('graphelement').width).

Note that older versions of IE use currentStyle. (it appears only IE9+ support getComputedStyle) document.getElementById('graphelement').currentStyle.width

Here's a jsFiddle demoing how to support both.

Snuffleupagus
  • 6,365
  • 3
  • 26
  • 36
3

I think you need to use window.getComputedStyle()

var gLabel = document.getElementById("graphelement");
var style = window.getComputedStyle(gLabel , null);

document.getElementById('graphlabel2').style.width = style.getPropertyValue("height");
NickSlash
  • 4,758
  • 3
  • 21
  • 38
0

Using document.getElementById, you can't get css values, only set them.

I think this is what you're looking for.

Community
  • 1
  • 1
SomeKittens
  • 38,868
  • 19
  • 114
  • 143
0

The .style property is for getting styles that were placed directly on the element. It doesn't compute styles from your stylesheets.

Refer this: why javascript this.style[property] return an empty string?

Community
  • 1
  • 1
Jashwant
  • 28,410
  • 16
  • 70
  • 105