jQuery - How to check if element visibility property is hidden

← Prev

CSS display and visibility properties control the visibility of an element, although both properties perform differently. However, the method (using jQuery) to check if an elements visibility is hidden is quite simple. In-fact its similar to the method we often use to check if elements display is none.

See this example. I am using jQuery .css() function to check if the "visibility" property of the element is "hidden".

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  
    <style>
      div { 
        width: 100%; 
        clear: both; 
      }

      p { 
        float: left;
        padding: 10px;
        width: auto;
      }
      p:nth-child(2n+1) { visibility: hidden; }
    </style>
</head>

<body>
  <div>
    <p> alpha </p>	<!--visibility: hidden-->
    <p> bravo </p>      
    <p> charlie </p>    <!--visibility: hidden-->
    <p> delta </p>
    <p> echo </p>	<!--visibility: hidden-->
  </div>

  <div>
    <input type='button' value='Click it' id="bt">
  </div>
</body>

<script>
  $('#bt').click(function () {
    check_if_hidden()
  });

  let check_if_hidden = () => {
    $('p').each(function () {      
      
      // check if elment is visibility: hidden.
      if ($(this).css('visibility') == 'hidden')  {
        alert('element "' + $(this).html() + '" is hidden ');
        
        $(this).css('visibility', 'visible'); // set property as 'visible';
      }
    });
  }
</script>
</html>
Try it

Difference between visibility: hidden and display: none

There is difference between visibility: hidden and display: none properties.

visibility: hidden will hide the element, but it takes up space on the web page. The elements remain hidden. See this example again. It show elements "bravo" and "delta", and there's lot of space between the two elements.

However, when you set display: none to an element, it removes the element from the web page. Elements, with "display: none" are never rendered. Check this out.

Also read... How to change CSS display to none or block using jQuery.

Happy coding. 🙂

← Previous