How to use the closest() method In JQuery

The closest() method can be used to get the elements that are closer to the clicked element where we can pass the element we have to hide as an argument to the closest() method to filter it and check for its length. If it is 0, then hide the element. Otherwise, keep the element in the document.

Syntax:

$('element_selector').closest('filter_param');

Example: The below example explains the use of the closest() method to hide an element on click to its surroundings using jQuery.

html




<!DOCTYPE html>
<html>
 
<head>
    <title>
        How to hide a div when the user
        clicks outside of it using jQuery?
    </title>
 
    <style>
        .container {
            height: 200px;
            width: 200px;
            background-color: green;
            border: 5px solid black;
        }
    </style>
 
    <script src=
"https://code.jquery.com/jquery-3.4.0.min.js">
    </script>
</head>
 
<body>
    <center>
        <h1 style="color: green">
            w3wiki
        </h1>
 
        <b>
            How to hide a div when
            the user clicks
            outside of it using jQuery?
        </b>
 
        <p>
           Click outside the
           green div to hide it
        </p>
 
        <div class="container" style="color:green"></div>
    </center>
    <script type="text/javascript">
        $(document).mouseup(function (e) {
            if ($(e.target).
                closest(".container").
                length=== 0) {
                $(".container").hide();
            }
        });
    </script>
</body>
 
</html>


Output:

How to hide a div when the user clicks outside of it using jQuery?

In this article, we will learn how an element can be hidden on click to its surroundings using jQuery. An element can be shown or hidden when clicked outside of it using the methods discussed below:

Table of Content

  • Using the closest() method
  • By checking whether element is clicked or its surroundings

Similar Reads

Using the closest() method

The closest() method can be used to get the elements that are closer to the clicked element where we can pass the element we have to hide as an argument to the closest() method to filter it and check for its length. If it is 0, then hide the element. Otherwise, keep the element in the document....

By checking whether element is clicked or its surroundings

...