PDA

View Full Version : .style.display Property Not Properly Recognized in External Stylesheet



NanakiXIII
Apr 9th, 2007, 08:38 PM
Well, I did my best to give this post an adequate title, but I'm finding it hard to properly describe the situation in a small amount of words. For that reason also, I've had little luck searching for an answer, so if my question is an elementary one that I could've found in the first thirty Google hits with the right query, I'm hoping this explanation will cool the flaming.

I also apologize if this post is considered to be in the wrong forum. I chose HTML & CSS over Javascript because it seems to be a problem to do with the CSS, but I might be mistaken.

To the point. Basically, I've got a div, in an external stylesheet I've got the following CSS for the div's class:



background-color: transparent;
height: 15px;
vertical-align: middle;
width: 160px;
margin-left: 20px;
display: none;


Note specifically the display: none;.

Using Javascript, however, the following boolean expression returns false:



if(document.getElementById(sub).style.display == "none")


The variable sub, in this case, holds the ID of the div in question. This works fine, as shows in other applications of the code that are beside the point right now. The Javascrips isn't the problem.

It should return true, I imagined. Next I added the following property to my div:

[code]
style="display: none;"
[code]

Now the same code returns true. I think the crux of my question should be clear by now: why does the Javascript code return false when the display:none; is in an external CSS stylesheet, and true when it is in my HTML as an attribute?

Arbitrator
Apr 9th, 2007, 09:29 PM
It returns false in the first example and true in the second because you’re testing for the value of the style attribute with element.style.property. The style attribute is not specified in the first example (or the display property is not set to none, at least, via that method) and, thus, when you test whether or not it is, the browser returns false.

To check the actual (computed) style currently in effect, you need to use getComputedStyle() for browsers that support DOM2 Style or currentStyle for browsers made by Microsoft.

NanakiXIII
Apr 9th, 2007, 09:44 PM
I see. Thanks for shedding some light on that. I'll have a look, though I'm afraid the lazy coder in me is going to be strongly suggesting to just use my attribute workaround.

_Aerospace_Eng_
Apr 9th, 2007, 09:50 PM
http://www.javascriptkit.com/dhtmltutors/dhtmlcascade4.shtml

NanakiXIII
Apr 10th, 2007, 02:40 PM
Guess it's not all that complicated, thanks for the link.