DEV Community

Nicholas Stimpson
Nicholas Stimpson

Posted on

Is this element visible?

The sample couldn't be much simpler. The question is, is the div element containing the text "Hello World" visible or hidden?

Visible right? Well maybe. jQuery begs to differ!

The problem lies is jQuery's (and widely copied) definition and implementation of its check for visibility. The definition is

Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero.

The implementation is

!! (el.offsetWidth || el.offsetHeight || el.getClientRects().length)

The div in question has a CSS property display value of "contents", which means that it creates no layout box of its own. Its child elements' layout boxes are instead directly connected to its parent layout box. The CSSOM specifications say that offsetWidth, offsetHeight and getClientRects().length must all return zero for such an element

For both offsetWidth and offsetHeight If the element does not have any associated CSS layout box return zero and terminate this algorithm.

for getClientRects() If the element on which it was invoked does not have an associated layout box return an empty DOMRectList object and stop this algorithm.

So in the light of this, what should be done? The intuitive answer clearly doesn't tally with the technical details. And it's not clear to me from a developer perspective whether an element with no layout box really should be considered visible, just because its contents are. Yet from a user perspective it seems obvious that it should. Do we need a third state beyond "visible" and "hidden"?

Top comments (2)

ahferroin7 profile image
Austin S. Hemmelgarn

I think the answer is that we need a better definition of 'visible' versus 'hidden'.

The problem is, there's no easy definition, because:

  • Elements can have no layout box, but still be rendered (such as your display: contents example).
  • Elements can have a layout box, but not actually show anything (such as an element with opacity: 0).
  • It's technically dependent on the media type and the attributes of the element, not just the styling. An element marked as hidden using ARIA attributes is not 'visible' if a screen reader is being used for example.
asmani2022 profile image

Element prototype isVisible = function { return !!( this.offsetWidth || offsetHeight || getClientRects().length (length); };