8

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?

Community
  • 1
  • 1
EoghanM
  • 20,021
  • 21
  • 80
  • 110

6 Answers6

14

From 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.

  • 3
    Good idea. It's even specified: http://www.w3.org/TR/cssom-view/#offset-attributes – Kornel Dec 03 '08 at 00:15
  • 1
    In the current CSSOM View Module draft (2013) the link posted by @Kornel does not point to the right section anymore. Check out [w3.org/TR/cssom-view/#dom-htmlelement-offsettop](http://www.w3.org/TR/cssom-view/#dom-htmlelement-offsettop). – falconepl Oct 10 '15 at 18:15
1

Using Prototype:

if($('someDiv').visible) {...}
Diodeus - James MacFarlane
  • 107,156
  • 31
  • 147
  • 171
0

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.

EoghanM
  • 20,021
  • 21
  • 80
  • 110
0

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.

  • Care to elaborate? If it's in the standard, supported by the standards-compliant crowd (FF, WebKit, …), and supported by the non-compliant gorilla, what makes it brittle? – Ben Blank Jan 13 '09 at 19:20
0

.getClientRects() will return an empty array if the element is not displayed by inheritance (display="none" from parent/ancestor element)

Paul Roub
  • 35,100
  • 27
  • 72
  • 83
Emmanuel Sellier
  • 420
  • 1
  • 4
  • 11
0

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);
}