WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

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

Topic: JavaScript / jQueryPrev|Next

Answer: Use the jQuery :visible and :hidden Selector

You can simply use the jQuery :visible or :hidden selector to select all the visible or hidden elements in an 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.

Let's try out the following example to understand how this basically works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get All Visible and Hidden Elements</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<style>
    .box{
        padding: 50px;
        margin: 20px 0;
        display: inline-block;
        font: bold 22px sans-serif;
        background: #f4f4f4;
    }
    .hidden{
        display: none;
    }
</style>
<script>
$(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:

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties