This is not to be confused with "How to tell if a DOM element is visible?"
I want to determine if a given DOM element is visible on the page.
E.g. if the element is a child of a parent which has display:none;
set, then it won't be visible.
(This has nothing to do with whether the element is in the viewport or not)
I could iterate through each parent of the element, checking the display
style, but I'd like to know if there is a more direct way?
This is not to be confused with "How to tell if a DOM element is visible?"
I want to determine if a given DOM element is visible on the page.
E.g. if the element is a child of a parent which has display:none;
set, then it won't be visible.
(This has nothing to do with whether the element is in the viewport or not)
I could iterate through each parent of the element, checking the display
style, but I'd like to know if there is a more direct way?
6 Answers
Reset to default 14From a quick test in Firefox, it looks like the size and position properties (clientWidth, offsetTop etc.) all return 0 when an element is hidden by a parent being display:none
.
Using Prototype:
if($('someDiv').visible) {...}
As I'm using MochiKit, what I came up with based on Ant P's answer was:
getElementPosition('mydiv').y != 0
I can also check whether it's in the viewport (vertically) by:
y = getElementPosition('mydiv').y
(y < getViewportPosition().y + getViewportDimensions().h &&
getViewportPosition().y < y)
Incidentally this also works in IE6.
Relying on the position being 0 is brittle. You're better off writing a helper function to iterate through the parents to check their display style directly.
Here's the iterative solution -
var elementShown = function(e){
if (e == document)
return true;
if ($(e).css('display') == 'none') //or whatever your css function is
return false;
return elementShown(e.parentNode);
}
.getClientRects()
will return an empty array if the element is not displayed by inheritance (display="none"
from parent/ancestor element)