hamze torabzade
hamze torabzade

Reputation: 7311

Using elements that are added to an array with (document.getElementById('ID'))

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!

Upvotes: 4

Views: 3093

Answers (3)

mplungjan
mplungjan

Reputation: 177965

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);

Upvotes: 0

Quentin
Quentin

Reputation: 943579

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.

Upvotes: 2

Ibu
Ibu

Reputation: 43810

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'));

Upvotes: 6

Related Questions