I disagree with the other answer, style.display
is only for inline properties, for this you will have to use getComputedStyle
, currentStyle
, attribute type="hidden"
on element <input>
.
With getComputedStyle
(and currentStyle
) we are able to check the visibility
and display
properties, both in the style=""
attribute and in the <style>
tag, and in properties within CSS files that are affecting elements in current page.
function getStyle(elem, prop)
{
if (elem.currentStyle) { //IE8
//Converte hifens para camelCase
prop = prop.replace(/-([a-z])/gi, function (value) {
return value.toLowerCase();
});
return elem.currentStyle[prop];
} else if (window.getComputedStyle) {//Navegadores modernos
//Converte camelCase para hifens
prop = prop.replace(/([A-Z])/g, '-$1').toLowerCase();
return window.getComputedStyle(elem, null).getPropertyValue(prop);
}
}
function isVisible(elem)
{
//Verifica inputs
if (/^(input|select|textarea)$/i.test(elem.nodeName) && elem.type === "hidden") {
return false;
}
//Verifica a propriedade visibility
if (getStyle(elem, "visibility") === "hidden") {
return false;
}
//Verifica a propriedade display
if (getStyle(elem, "display") === "none") {
return false;
}
return true;
}
function isHidden(elem)
{
return !isVisible(elem);
}
#ELEMENTO_1 {
visibility: hidden;
}
#ELEMENTO_3 {
display: none;
}
<div id="ELEMENTO_1">Invisivel visibility: hidden</div>
<button onclick="console.log(isVisible(document.getElementById('ELEMENTO_1')));">Testar visibility: hide</button>
<hr>
<div id="ELEMENTO_2">Visivel</div>
<button onclick="console.log(isVisible(document.getElementById('ELEMENTO_2')));">Testar Visivel</button>
<hr>
<div id="ELEMENTO_3">Invisivel display: none</div>
<button onclick="console.log(isVisible(document.getElementById('ELEMENTO_3')));">Testar display: none</button>
<hr>
<input type="hidden" id="ELEMENTO_4">
<button onclick="console.log(isVisible(document.getElementById('ELEMENTO_4')));">Testar input[type=hidden]</button>
Examples:
var el = document.getElementById("meuId");
alert(isVisible(el)); //Retorna true se visivel, caso contrário retorna false
alert(isHidden(el)); //Retorna true se oculto, caso contrário retorna false