2

While walking HTML5 DOM tree I want to determine whether each element is a block level element or inline element.

var divElement = document.getElementById('foo');
alert(divElement.style.display)
alert(window.getComputedStyle(divElement, null).getPropertyValue('display'))

I see that the first alert displays a null-string while the second alert displays 'block', so I think the second technique is what I need to use. Here is a jsfiddle: http://jsfiddle.net/UaFpv/

I want to know if there is any downside to using ​window.getComputedStyle(divElement, null).getPropertyValue('display') to do my job, like cross-browser compatibility issues, etc. Are there any other techniques that can solve this problem?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Lone Learner
  • 18,088
  • 20
  • 102
  • 200

1 Answers1

5

Old IE versions do not support getComputedStyle. For IE, use the currentStyle property:

divElement.currentStyle['display'];

Implemented in your code:

var divElement = document.getElementById('foo');
var displayStyle;
if (divElement) { // Only if the element exists
    if (window.getComputedStyle) {
        displayStyle = window.getComputedStyle(divElement, null).getPropertyValue('display');
    } else {
        displayStyle = divElement.currentStyle.display;
    }
}
alert(displayStyle);
Rob W
  • 341,306
  • 83
  • 791
  • 678