Ishan
Ishan

Reputation: 3395

how to check the value of display property of a header element?

I need to check the display property of a header element on the page. Based on it different operations are to be done. I tried using

document.getElementsByTagName('header')[0].style.display

and comparing it to various display attributes, but this is executing false part whatever property I check for. Here is my html :

<body>
    <header id="main">
        <p>Test to find the display property of an element (header in this case).</p>
    </header>
</body>

And here is my Javascript :

var test1 = document.createElement('div');
var test2 = document.createElement('div');

test1.innerText = 'Testing for block : ';
test2.innerText = 'Testing for none : ';

var body = document.getElementById('main');

if (document.getElementsByTagName('header')[0].style.display == 'block') {
    test1.innerText = test1.innerText + 'true part is executed';
    body.appendChild(test1);
} else {
    test1.innerText = test1.innerText + 'false part is executed';
    body.appendChild(test1);
}

if (document.getElementsByTagName('header')[0].style.display == 'none') {
    test2.innerText = test2.innerText + 'true part is executed';
    body.appendChild(test2);
} else {
    test2.innerText = test2.innerText + 'false part is executed';
    body.appendChild(test2);
}

I put this also on jsfiddle http://jsfiddle.net/n8zDc/1/

What am I doing wrong ?

Upvotes: 1

Views: 1105

Answers (1)

bevacqua
bevacqua

Reputation: 48486

You want to use window.getComputedStyle. You haven't defined a display property value anywhere in the DOM

var header = document.getElementById('main');
var style = window.getComputedStyle(header);
console.log(style.display);

The reason is that .style doesn't really compute which style is actually applied to the element, but simply the style attribute on the DOM (either the HTML, or applied through JavaScript). As an example, consider this CSS:

* {
  float: right;
}

.foo {
  float: left;
}

And HTML:

<div>Foo</div>
<div class='foo'>Bar</div>

Neither of these have any style values in them, yet their computed styles will have a bunch of values, browser defaults such as display: block, and the CSS rules applied to them.

Upvotes: 2

Related Questions