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

  323 views   6 months ago jQuery

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-1.12.4.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>

 

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com

Related Articles