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!

Answers:

Answer

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

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.

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.