I could just check the element's style.display property to make sure it doesn't equal 'none', but if its parent element has "display:none;" set, the child element would be hidden but I don't think its own style.display property would have a value?

Is there a reliable way to detect if an element is visible on the page? I'm not worried about the element being obscured by other content, I'm happy to classify that as visible. The main purpose is to write a javascript function HasElementBeenHidden to see if an element on the page has been intentionally hidden from the user.

This is to run within a Selenium test. An example use case would be detecting if a web page was showing a "Loading" div. This div is always present in the HTML, but is only made visible during long running tasks. I'd like to be able to detect if such a div is currently being displayed to the user.

2 answers

6
points
This was chosen as the best answer

jQuery does it by testing the element's offsetWidth and offsetHeight. If I understand correctly, if both are equal to 0, the element is invisible (with the exception of some tr and td elements). There's more around that here.

Answered over 7 years ago by Olly Hodgson
danwellman 5600
3
points

Yeah, the child of an element that has display:none will have whatever display value is set for it, even if it is not visible...

You can use jQuery's :visible filter to get a collection of visible elements and this does take parents into consideration as opposed to just looking at the display property

Or you could manually travel up the tree looking at parent elements to see if display:none is set on any parent?

Answered over 7 years ago by danwellman