I'm interested in a way to check whether an element has display:none style explicility (ie style="display:none"), has a class that has (or inherits) this style, or one of its parents is hidden (and my element inherits this)
Case1:
<body><div><span style="display:none;">Some hidden text</span></div>
or
<body><div style="display:none;"><span>Some hidden text</span></div>
Case2:
SomeClass { display:none; }
<body><div class="SomeClass"><span>Some hidden text</span></div>
Thanks,
We can do the following to check an element's visibility in the viewport: Get the bounding rect of the DOM element using the getBoundingClientRect . This method returns an object with an element's width, height, and position relative to the viewport.
The visibility property sets or returns whether an element should be visible. The visibility property allows the author to show or hide an element. It is similar to the display property.
Another way to check if an element is hidden is to use the window. getComputedStyle() method. It will return the display property value of the object. We can check if the string is equal to none meaning the element is hidden and do something.
Summary. Use the getBoundingClientRect() method to get the size of the element and its relative position to the viewport. Compare the position of the element with the viewport height and width to check if the element is visible in the viewport or not.
You are looking for one solution to two different scenarios.
The first scenario is getting the cascaded/computed style for a css property. See this answer for how to do that.
The second scenario is detecting if any of an element's parents are hidden. This requires traversing and is cumbersome and slow.
You can take the solution outlined here (and employed by jQuery/Sizzle since 1.3.2), and just read the dimensions of the element:
var isVisible = element.offsetWidth > 0 || element.offsetHeight > 0;
If it has dimensions then it is visible in the sense that it takes up some rectangular space (however small) in the document. Note that this technique still has some downsides for certain elements in certain browsers, but should work in most cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With