ZYX
ZYX

Reputation: 69

Visibility values defined in CSS not showing in Javascript

The following code produces the result one would expect:

<script>
function Show_Visibility(){
    p = document.getElementById("i_button_2");
    alert(p.style.visibility);
}
</script>

<INPUT TYPE = "button"   id = "i_button_1"  value = "This is Button 1"   onclick="Show_Visibility()">
<br>
<INPUT TYPE = "button"   id = "i_button_2"  value = "This is Button 2">

<script>
p = document.getElementById("i_button_2");
p.style.visibility = "hidden";
</script>

However if we define the visibility of button 2 as hidden in CSS, the button is indeed hidden when the page is loaded, but the Javascript alert message is blank.

#i_button_2{visibility: hidden;}

<script>
function Show_Visibility(){
    p = document.getElementById("i_button_2");
    alert(p.style.visibility);  
}
</script>

<INPUT TYPE = "button"   id = "i_button_1"  value = "This is Button 1"   onclick="Show_Visibility()">
<br>        
<INPUT TYPE = "button"   id = "i_button_2"  value = "This is Button 2">

Why is this happening?

Upvotes: 1

Views: 71

Answers (1)

lxe
lxe

Reputation: 7599

You should use getComputedStyle to get the styles applied via stylesheets:

alert(getComputedStyle(p).visibility); 

From the MDN article:

The object returned from getComputedStyle is read-only and can be used to inspect the element's style (including those set by a element or an external stylesheet). The elt.style object should be used to set styles on a specific element.

Upvotes: 2

Related Questions