Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • jQuery Tutorial
  • jQuery Selectors
  • jQuery Events
  • jQuery Effects
  • jQuery Traversing
  • jQuery HTML & CSS
  • jQuery AJAX
  • jQuery Properties
  • jQuery Examples
  • jQuery Interview Questions
  • jQuery Plugins
  • jQuery Cheat Sheet
  • jQuery UI
  • jQuery Mobile
  • jQWidgets
  • Easy UI
  • Web Technology
Open In App
Next Article:
jQuery contents() Method
Next article icon

jQuery closest() Method

Last Updated : 07 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

The closest() is an inbuilt method in jQuery that returns the first ancestor of the selected element in the DOM tree. This method traverses upwards from the current element in the search of first ancestor of the element. Document Object Model (DOM) is a World Wide Web Consortium standard. This defines for accessing elements in the DOM tree.

Syntax:

$(selector).closest(para1, para2);

Parameter: It accepts two parameters which are specified below-

  • para1: This specifies the element to narrate the ancestor search in the DOM tree.
  • para2: This is an optional parameter DOM element within which a matching element is found.

Return Value: It returns the first ancestor for the selected element.

jQuery code to show the working of closest() method:

Example 1: In the below code, optional parameter is not passed.

html




<!DOCTYPE html>
<html>
 
<head>
    <style>
        .main * {
            display: block;
            border: 2px solid lightgrey;
            color: grey;
            padding: 5px;
            margin: 15px;
        }
    </style>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
   </script>
    <script>
        // here is the script code for performing the method
        $(document).ready(function () {
            $("span").closest("ul").css({
                "color": "green",
                "border": "2px solid green"
            });
        });
    </script>
</head>
 
<body class="main">
    This is great-great grand parent element !
    <div style="width:600px;">
        This is great grand parent element !
        <ul>
            This is the second ancestor element !
            <ul>
                <!-- This element will be selected -->
                This is first ancestor element !
                <li>This is direct parent !
                    <span>
                        This is span the child element !
                    </span>
                </li>
            </ul>
        </ul>
    </div>
</body>
 
</html>
 
 

Output:

Example 2: In the below code, optional parameter is passed to the method.

html




<!DOCTYPE html>
<html>
 
<head>
    <style>
        .main * {
            display: block;
            border: 2px solid lightgrey;
            color: grey;
            padding: 5px;
            margin: 15px;
        }
    </style>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            //Here among dom id first ancestor will select
            let item = document.getElementById("dom");
            $("li").closest("ul", item).css({
                "color": "green",
                "border": "2px solid green"
            });
        });
    </script>
</head>
 
<body class="main">
    This is great-great-grandparent !
    <div style="width:500px;">
        div (great-grandparent)
        <ul id="dom">
            This is second ancestor !
            <ul id="dom">
                This is first ancestor !
                <li>This is direct parent !
                    <span>
                        This is span the child one !
                    </span>
                </li>
            </ul>
        </ul>
    </div>
</body>
 
</html>
 
 

Output:

jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”. You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.



Next Article
jQuery contents() Method

K

kundankumarjha
Improve
Article Tags :
  • JQuery
  • Web Technologies
  • jQuery-Methods

Similar Reads

  • jQuery add() method
    The jQuery add() method is used to add elements to the existing group of elements. This method can add element to the whole document, or just inside the context element if the context parameter is defined. Syntax: $(selector).add(element, context_parameter) Here selector helps to find the matching e
    1 min read
  • jQuery addBack() Method
    The addBack() is an inbuilt method in jQuery that adds the previous set of elements to the current set. This method adds previous DOM tree elements to the current set and maintains them in the internal stack which will take care of changes to the matched set of elements. Syntax: .addBack(selector) P
    2 min read
  • jQuery children() Method
    jQuery children() method is used to find all the child elements of the selected element. This children() method in jQuery traverses down to a single level of the selected element and returns all child elements. Syntax:$(selector).children()Parameter: It accepts an optional parameter that specifies t
    2 min read
  • jQuery closest() Method
    The closest() is an inbuilt method in jQuery that returns the first ancestor of the selected element in the DOM tree. This method traverses upwards from the current element in the search of first ancestor of the element. Document Object Model (DOM) is a World Wide Web Consortium standard. This defin
    2 min read
  • jQuery contents() Method
    The contents() is an inbuilt method in jQuery that returns all the direct children, including text and comment nodes for the selected element. Syntax: $(selector).contents()Parameter: It does not accept any parameter. Return Value: It returns all the direct children elements of the selected element.
    2 min read
  • jQuery Misc each() Method
    The each() Method in jQuery is used to specify the function to run for each matched element. Syntax: $(selector).each(function(index, element)) Parameters: This method accepts single parameter function(index, element) which is mandatory. It is used to run for each matched element. It contains two pa
    2 min read
  • jQuery eq() Method
    The eq() method is an inbuilt method in jQuery that is used to locate the selected elements directly and returns an element with a specific index. Syntax: $(selector).eq(index)Parameters: Here the parameter "index" specifies the index of the element.Can either be positive or a negative number. NOTE:
    2 min read
  • jQuery filter() Method
    The jQuery is a very powerful tool which helps us to incorporate a variety of DOM traversal methods to select elements in a document randomly or in sequential order. Most of the DOM traversal methods do not modify the elements whereas they filter them out upon the given conditions. The filter() meth
    2 min read
  • jQuery find() Method
    The find() is an inbuilt method in jQuery which is used to find all the descendant elements of the selected element. It will traverse all the way down to the last leaf of the selected element in the DOM tree. Syntax: $(selector).find() Here selector is the selected elements of which all the descenda
    2 min read
  • jQuery first() Method
    The jQuery first() method selects and returns the first element from a set of matched elements. It's commonly used to manipulate or retrieve the first element within a group, ensuring that operations only apply to the first match. Syntax:  $(selector).first()Here selector is the main class of all th
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences