Open In App

How to get/set elements containing the closest parent element matches the specified selector using jQuery ?

In this article, we will learn how to get a set of elements containing the closest parent element that matches the specified selector, the starting element included using jQuery.

JQuery is the fastest and lightweight JavaScript library that is used to simplify the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. JQuery is widely famous for its motto of “Write less, do more.” It simply means that you can achieve your goal by just writing a few lines of code.



Approach: We will use the closest() method of jQuery for this purpose. This method is used for accessing the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

Syntax:



.closest( selector, context )

 

Parameters: It has the following parameters as mentioned above and described below.

The below examples will demonstrate the above approach.

Example:




<!doctype html>
<html lang="en">
  
<head>
    <style>
        li {
            margin: 3px;
            padding: 3px;
            background: lightgrey;
        }
  
        li.highlight {
            background: lightgreen;
        }
  
        body {
            text-align: center;
        }
    </style>
    <script src=
    </script>
</head>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
  
    <ul>
        <li><b>A computer science portal for geeks.</b></li>
        <li>GeeksforGeeks<b> A computer science portal
            for geeks</b></li>
    </ul>
  
    <script>
        $(document).on("click", function (event) {
            $(event.target)
              .closest("li")
              .toggleClass("highlight");
        });
    </script>
</body>
  
</html>

Output:


Article Tags :