JavaScript cannot display linked style value(s)

I tried using JavaScript to check if a div is visible or not using an alert. Whether using class or id, if visibility is in a linked .css file, alert(document.getElementById("ID").style.visibility);
displays nothing (blank). alert(document.getElementById("ID").style.visibility.value); displays Undefined. If the style is within the div tag itself however <div id="ID" style="visibility: visible;"> alert(document.getElementById("ID").style.visibility); displays visible. Is this normal behaviour?

Yes, that is expected behavior, even if it might not make sense at first sight. The reason for this is explained at the related MDN page. What style returns is the inline style, i.e. only the properties that are defined in the style attribute of the element. That’s why it returns an empty string when not set via style.

In order to get the applied style of a CSS property, you need to use window.getComputedStyle(document.getElementById("ID")). So to get the value of the visibility property you need to call window.getComputedStyle(document.getElementById("ID")).getPropertyValue("visibility").

There is also a newer, little bit shorter method computedStyleMap(), which also much more flexible, though the related specification is not finished yet and therefore not available in all browsers yet. With that you get the value of the visibility property via document.getElementById("ID").computedStyleMap().get("visibility").value.

Bonus tip: Use console.log() instead of alert()! That allows you to inspect the variable within the console of your favorite browser’s DevTools.

Sebastian