published: 22 May 2022
2 min read
How to check if an element is hidden or visible using JavaScript
In JavaScript, the quickest way to check if an element is hidden or visible in DOM is to use the getComputedStyle()
method. This method returns the actual values of CSS properties used to render an HTML element in DOM.
Let us say that we have got the following hidden HTML element:
.hidden {
display: none;
}
<button>Click Me!</button>
An HTML element can be hidden due to either display:none
or visibility:hidden
CSS properties.
Let us write a function that checks both these properties and returns a boolean value depicting the visibility status of the element:
const isHidden = elem => {
const styles = window.getComputedStyle(elem)
return styles.display === 'none' || styles.visibility === 'hidden'
}
const elem = document.querySelector('button')
if (isHidden(elem)) {
console.log('Element is hidden!!')
} else {
console.log('Element is visible!!')
}
// Element is hidden!!
If you are using jQuery, you can use the :hidden
and :visible
selectors to check if a DOM element is hidden or visible:
// Check if element is hidden
if ($('button').is(':hidden')) {
console.log('Element is hidden!!')
}
// Check if element is visible
if ($('button').is(':visible')) {
console.log('Element is visible!!')
}
Are we missing something? Help us improve this article. Reach out to us.
How to check if an element is hidden or visible using JavaScript
In JavaScript, the quickest way to check if an element is hidden or visible in DOM is to use the getComputedStyle()
method. This method returns the actual values of CSS properties used to render an HTML element in DOM.
Let us say that we have got the following hidden HTML element:
.hidden {
display: none;
}
<button>Click Me!</button>
An HTML element can be hidden due to either display:none
or visibility:hidden
CSS properties.
Let us write a function that checks both these properties and returns a boolean value depicting the visibility status of the element:
const isHidden = elem => {
const styles = window.getComputedStyle(elem)
return styles.display === 'none' || styles.visibility === 'hidden'
}
const elem = document.querySelector('button')
if (isHidden(elem)) {
console.log('Element is hidden!!')
} else {
console.log('Element is visible!!')
}
// Element is hidden!!
If you are using jQuery, you can use the :hidden
and :visible
selectors to check if a DOM element is hidden or visible:
// Check if element is hidden
if ($('button').is(':hidden')) {
console.log('Element is hidden!!')
}
// Check if element is visible
if ($('button').is(':visible')) {
console.log('Element is visible!!')
}
Are you looking for other code tips?
JS Nooby
Javascript connoisseur