Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding appropriate parent with jQuery

Tags:

jquery

dom

parent

Given a DOM element how do I find its nearest parent with a given css class?

$(".editButton").click(function() {
   (magic container selector goes here).addClass("editing");
});

I don't want to use lots or $(...).parent().parent() since I don't want to be bound to a particular dom structure.

like image 463
Allain Lalonde Avatar asked Dec 18 '08 15:12

Allain Lalonde


2 Answers

This should work

$(this).parents('.classYouWant:first').addClass("editing");
like image 118
Bill Zeller Avatar answered Oct 05 '22 16:10

Bill Zeller


$( this ).closest( '.yourselector' )

As the name tells, finds the closest ancestor for this element.

like image 31
fiatjaf Avatar answered Oct 05 '22 17:10

fiatjaf