1

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?

1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.