4

Why does this code not work?

var all_obj_element= new Array();
all_obj_element[0]= document.getElementById('Img3');            
alert(all_obj_element[0].style.width);

The alert shows an empty box!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hamze
  • 7,061
  • 6
  • 34
  • 43

3 Answers3

6

Because you haven't set the width. Here is how you get the computed style value of an element:

var computedStyle = function (el,style) {
    var cs;
    if (typeof el.currentStyle != 'undefined'){
        cs = el.currentStyle;
    }
    else {
        cs = document.defaultView.getComputedStyle(el,null);
    }
    return  cs[style];
}

Now let's get the value:

var element = document.getElementById('Img3');

alert(computedStyle(element,'width'));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ibu
  • 42,752
  • 13
  • 76
  • 103
  • @hamze the computed style is the value computed when the stylesheet or in line style are processed – Ibu May 26 '11 at 06:24
2

The element with the id Img3 has not had its .style.width property set (which can be done by assigning a value to it via JavaScript, or by using the style attribute).

Quirks Mode has an article on how to read the computed style in a cross-browser fashion.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

If there is no need to see the STYLEd width, just look at the width:

var all_obj_element= [];
all_obj_element[0]= document.getElementById('Img3');            
alert(all_obj_element[0].width);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mplungjan
  • 169,008
  • 28
  • 173
  • 236