16

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.

4 Answers 4

31

This should work

$(this).parents('.classYouWant:first').addClass("editing"); 
Sign up to request clarification or add additional context in comments.

3 Comments

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: 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.
so :first, in this example, gets the nearest parent to $(this) with .classYouWant? so working it's way UP the DOM?
11
$( this ).closest( '.yourselector' ) 

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

1 Comment

+1 This one is my preference, when I know I'm only after 1 element
3

Use .parents(".yourClass") instead of .parent().

jQuery parents()

Comments

2

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

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.