How do you find if css properties are set in a certain way? For example how do you find if an element has a css property of background-color:#ff0000;
? Or if the element has a certain width etc...
Asked
Active
Viewed 4,640 times
0

William Green
- 83
- 1
- 11
-
1Do you mean you want to find properties set directly on the element using the `style` attribute, or you want to find the effective value of the element considering all CSS rules and the cascade? – Nov 15 '14 at 03:12
-
@WilliamGreen what you want is getComputedStyle. Look it up using google. If you use an external stylesheet then element.style.prop won't work – Daniel F Mar 01 '16 at 03:17
1 Answers
1
This is a way to determine it for all css properties including visibility: this works for properties set in a external css file, internal embedded styles, or inline styles! Note: the document MUST be loaded before executing the script!
I have tested this out and it works with css rules set in inline, embedded, and external.
html:
<div id="element" onload="test();">div content</div>
css:
#element
{
visibility:hidden;
}
javascript:
function test()
{
var element = document.getElementById('element');
if(element.style.visibility == 'hidden'){
alert('hidden');
}
if(element.style.visibility == 'visible')
{
alert('visible');
{
if(element.style.visibility == 'collapse')
{
alert('collapsed');
}
if(element.style.visibility == 'initial')
{
alert('initial');
}
if(element.style.visibility == 'inherit')
{
alert('inherit');
}
}
I have used this before.

William Green
- 83
- 1
- 11
-
Did you test this? It won't work. The CSS rule does **not** affect `element.style`. – Nov 15 '14 at 03:12
-
it seemed to work in another program I made. However just now in response to your comment I did some testing and the browser is giving me errors! I don't know why since it's the same code I used before and it worked! I don't get it! – William Green Nov 15 '14 at 03:32
-
-
That's it the document must be loaded before the script executes otherwise it will think that the element doesn't exist! – William Green Nov 15 '14 at 03:37
-
1The basic problem remains that the CSS rule will not do anything with or to `element.style.visibility`. It will start off, and remain, an empty string. Your little program is likely to display "visible", because the `element.style.visibility == 'hidden'` condition will be false. It might be nice to put up a fiddle or something to show your approach and validate that it works. – Nov 15 '14 at 04:08
-
I tried jsfiddle just now (thanks for the suggestion! I just got an account today). Unfortunately jsfiddle (in my particular situation) messed with the point I was trying to prove by automatically adding an window.onload! Therefor I didn't want to post it since it won't work unless the whole document has loaded. – William Green Nov 15 '14 at 15:02