How to select all visible or hidden elements in a page using jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the jQuery :visible and :hidden Selector

You can use the jQuery :visible or :hidden selector to select all the visible or hidden elements in a HTML page. The jQuery :visible selector considered an element visible if they consume space in the document. That means, elements with visibility: hidden; or opacity: 0; are considered visible, since they still preserve space in the layout.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>jQuery Get All Visible and Hidden Elements</title>
  • <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
  • <style type="text/css">
  •     .box{
  •         padding: 50px;
  •         margin: 20px 0;
  •         display: inline-block;
  •         font: bold 22px sans-serif;
  •         background: #f4f4f4;
  •     }
  •     .hidden{
  •         display: none;
  •     }
  • </style>
  • <script type="text/javascript">
  • $(document).ready(function() {
  •     // Get visible boxes
  •     $(".get-visible-btn").click(function(){
  •         var visibleBoxes = [];
  •         $.each($(".box"), function(){ 
  •             if($(this).is(":visible")) {
  •                 visibleBoxes.push($(this).text());
  •             }
  •             
  •         });
  •         alert("Visible boxes are - " + visibleBoxes.join(", "));
  •     });
  •     
  •     // Get hidden boxes
  •     $(".get-hidden-btn").click(function(){
  •         var hiddenBoxes = [];
  •         $.each($(".box"), function(){ 
  •             if($(this).is(":hidden")) {
  •                 hiddenBoxes.push($(this).text());
  •             }
  •         });
  •         alert("Hidden boxes are - " + hiddenBoxes.join(", "));
  •     });
  • });
  • </script>
  • </head>
  • <body>
  •     <div class="box">Box A</div>
  •     <div class="box hidden">Box B</div>
  •     <div class="box">Box C</div>
  •     <div class="box hidden">Box D</div>
  •     <div class="box">Box E</div>
  •     <br>
  •     <button type="button" class="get-visible-btn">Get Visible Boxes</button>
  •     <button type="button" class="get-hidden-btn">Get Hidden Boxes</button>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.