Open In App

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

Last Updated : 28 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  • selector: This specifies the element to be searched in the DOM tree. This can be a selector or a reference to the element.
  • context: This is an optional parameter within which the matching element is to be found.

The below examples will demonstrate the above approach.

Example:

HTML




<!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:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads