Check if element is hidden in JavaScript
Question:
How to check if element is hidden in JavaScript? Answer:
let el = document.getElementById('container');
let isHidden = el.offsetParent === null;
Description:
The HTMLElement.offsetParent
read-only property returns a reference to the element which is the closest (nearest in the containment hierarchy) positioned ancestor element. If there is no positioned ancestor element, the nearest ancestor td, th, table will be returned, or the body if there are no ancestor table elements either.
offsetParent returns null in the following situations:
- The element or its parent element has the
display
property set tonone
. - The element has the
position
property set tofixed
(firefox returns).
- The element is
or
.
Reference:
offsetParent reference
Share "How to check if element is hidden in JavaScript?"
Related snippets:
- Create HTML element with attributes in JavaScript
- Get element by ID in React
- Set the required attribute in JavaScript
- Get elements by data attribute in JavaScript
- Add class to the clicked element in JavaScript
- Add class to multiple elements in JavaScript
- Add class to element if it does not already exists with JavaScript
- Add data attribute to element in JavaScript
- Add CSS class to body with JavaScript
- Add class to parent element in JavaScript
- Toggle fullscreen and normal mode with JavaScript
- Play video in fullscreen with vanilla JavaScript
- Select HTML elements by CSS selectors in vanilla JavaScript
- Exit from fullscreen mode on click in JavaScript
- Switch browser to fullscreen mode with JavaScript
- Get the value of text input field in JavaScript
- Get element with data- attribute using vanilla JavaScript
- Get the value of selected radio button in JavaScript
- Get selected option from select using JavaScript
- Check if element is hidden in JavaScript
Tags:
element hidden, check element visibility, offsetParent, hidden Technical term:
Check if element is hidden in JavaScript