Skip to content

How do I check if an element is hidden in jQuery?

  • by

In jQuery, you can use the is() method with the :hidden selector to check if an element is hidden. Here’s an example. To do this, select the element using its ID or class, and then use the is() method with the :hidden selector to determine if the element is currently hidden.

HTML

<div id="myElement" style="display:none;">This is a hidden element</div>

JavaScript

if ($('#myElement').is(':hidden')) {
  console.log('The element is hidden');
} else {
  console.log('The element is visible');
}

In this example, we’re using jQuery’s is() method to check if the #myElement div is hidden. We’re passing the :hidden selector as an argument to is(), which returns true if the element is hidden and false otherwise.

Check if an element is hidden in the jQuery example

Here is a simple complete HTML code example that demonstrates how to check if an element is hidden in jQuery:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Check if an Element is Hidden in jQuery</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
      $(document).ready(function() {
        if ($('#myElement').is(':hidden')) {
          console.log('The element is hidden');
        } else {
          console.log('The element is visible');
        }
      });
    </script>
  </head>
  <body>
    <div id="myElement" style="display:none;">This is a hidden element</div>
  </body>
</html>

Output:

How do I check if an element is hidden in jQuery?

We’re including the jQuery library in the <head> section of the HTML document using a CDN link. We’re also defining a <script> block that checks if the #myElement div is hidden using the is() method and the :hidden selector. If the element is hidden, we’re logging a message to the console.

In the <body> section of the HTML document, we’re defining the #myElement div with a display value of none, which means that it will be hidden by default.

Do comment if you have any doubts or suggestions on this jQuery topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *