Open In App

How to hide elements defined as variables in jQuery ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to hide elements defined as variables in jQuery. These can be done using two approaches.

Approach 1: In this approach, we will first select the element that has to be hidden and then assign it to a variable. We will then call the hide() method on the variable. This method will hide the element from the page.

Example:

HTML




<!DOCTYPE html>
<html>
<head>
    <script src=
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                // Getting the element with the id
                // of "dsa" in a variable
                let dsaGFG = $("#dsa");
                // Hiding the element using the
                // hide() method
                dsaGFG.hide();
            })
        });
    </script>
</head>
 
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
 
    <p id="faang">FAANG</p>
 
    <p id="dsa">DSA</p>
 
    <p id="cp">CP</p>
 
    <p id="algo">ALGO</p>
 
    <button>Hide Element</button>
</body>
</html>


Output:

Approach 2: In this approach, we will first select the element that has to be hidden and then assign it to a variable. We will then call the addClass() method on the variable. This will add a CSS class that we will create next. This CSS class will contain the display property that is set to none, effectively hiding the element.

Example:

HTML




<!DOCTYPE html>
<html>
<head>
    <style>
        /* Define the class to
       be added */
        .hiddenClass {
 
            /* Setting the display
         to none hides the element */
            display: none;
        }
    </style>
    <script src=
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
 
                // Getting the element with the id
                // of "cp" in a variable
                let cpGFG = $("#cp");
 
                // Hiding the element by adding a
                // class using the addClass() method
                cpGFG.addClass("hiddenClass");
            })
        });
    </script>
</head>
 
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
 
    <p id="faang">FAANG</p>
 
    <p id="dsa">DSA</p>
 
    <p id="cp">CP</p>
 
    <p id="algo">ALGO</p>
 
    <button>Hide Element</button>
</body>
</html>


Output:



Last Updated : 06 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads