tags:

views:

1631

answers:

3

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.

+7  A: 

This should work

$(this).parents('.classYouWant:first').addClass("editing");
Bill Zeller
Am I not right in thinking that all jquery functions actually return a list. If so, you might want to do $(this).parents('.classYouWant:first') (try it!)
Jennifer
@Jennifer: You are correct, if the element had more than 1 parent it would set editing to all of them. You should have posted an answer. I'd accept it.
Allain Lalonde
so :first, in this example, gets the nearest parent to $(this) with .classYouWant? so working it's way UP the DOM?
CarolinaJay65
+1 .parent().parent().parent(), just felt really wrong...
James
+3  A: 

Use .parents(".yourClass") instead of .parent() http://docs.jquery.com/Traversing/parents#expr

rizzle
+2  A: 

You can use the parent selection. eg $(".myclass:parent").something(); will find all the elements with the class myclass that have children.

rikh
Although correct, it doesn't address the question since it's not find the parent for a particular dom element.
Allain Lalonde