Reputation: 2173
Is it possible to check if an element's CSS display == block
or none
using JavaScript?
Upvotes: 149
Views: 299203
Reputation: 3390
I just found the function element.checkVisibility()
which is returning false
when display: none
is set.
Honestly, I cannot find any documentation for it, so I do not know if it is Chrome specific.
Upvotes: 2
Reputation: 10071
As sdleihssirhc says below, if the element's display
is being inherited or being specified by a CSS rule, you'll need to get its computed style:
return window.getComputedStyle(element, null).display;
Elements have a style
property that will tell you what you want, if the style was declared inline or with JavaScript:
console.log(document.getElementById('someIDThatExists').style.display);
will give you a string value.
Upvotes: 193
Reputation: 42496
If the style was declared inline or with JavaScript, you can just get at the style
object:
return element.style.display === 'block';
Otherwise, you'll have to get the computed style, and there are browser inconsistencies. IE uses a simple currentStyle
object, but everyone else uses a method:
return element.currentStyle ? element.currentStyle.display :
getComputedStyle(element, null).display;
The null
was required in Firefox version 3 and below.
Upvotes: 93
Reputation: 18833
For jQuery, do you mean like this?
$('#object').css('display');
You can check it like this:
if($('#object').css('display') === 'block')
{
//do something
}
else
{
//something else
}
Upvotes: 44
Reputation: 508
This answer is not exactly what you want, but it might be useful in some cases. If you know the element has some dimensions when displayed, you can also use this:
var hasDisplayNone = (element.offsetHeight === 0 && element.offsetWidth === 0);
EDIT: Why this might be better than direct check of CSS display
property? Because you do not need to check all parent elements. If some parent element has display: none
, its children are hidden too but still has element.style.display !== 'none'
.
Upvotes: 21
Reputation: 490
Basic JavaScript:
if (document.getElementById("elementId").style.display == 'block') {
alert('this Element is block');
}
Upvotes: 5
Reputation: 4384
To find out if it's visible with plain JavaScript, check whether the display property is 'none' (don't check for 'block', it could also be blank or 'inline' and still be visible):
var isVisible = (elt.style.display != "none");
If you are using jQuery, you can use this instead:
var isVisible = $elt.is(":visible");
Upvotes: 3
Reputation: 20654
With pure javascript you can check the style.display
property. With jQuery you can use $('#id').css('display')
Upvotes: 0
Reputation: 489
You can check it with for example jQuery:
$("#elementID").css('display');
It will return string with information about display property of this element.
Upvotes: 1
Reputation: 4721
yes.
var displayValue = document.getElementById('yourid').style.display;
Upvotes: 8