Open In App

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

Last Updated : 28 Nov, 2021
Like Article

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.


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



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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads