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 class="hidden">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!!`)
}

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.