closest() method in jQuery
The closest()
method used the select first ancestor of the selected element.
Syntax
//select closest ul $("li").closest("ul"); //select closest tr $("td").closest("tr");
Example
The following example shows, how to select first ancestor of selected element using jQuery closest()
method.
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <style> div{ padding:20px; border:1px solid #000; } </style> </head> <body> <div class='box1'> <div class='box2'> <div class='box3'> <p>Hello</p> </div> </div> </div> <script> $(document).ready(function(){ $("p").closest(".box2").css("border","3px solid red"); }); </script> </body> </html>Try it Yourself