2

Consider this sample html

<div class="A">
    <div class="B">
        <span class="C">Sample text</span>
        <div class="D">
            <div class="E">Clickable Text</div>
        </div>
    </div>
</div>

And some jQuery

$(".E").click(function(){
    //body
});

What is the easiest way to get a parent of $(this) that matches a selector? For example, say in the example I need to get the div where class="A". At the moment because I know the structure of the html I could do

$(this).parent().parent();

But I'm looking for a way that would work regardless of the structure. Something along the lines of

$(this).findFirstParent(".A");

I hope I've been understandable.

3
  • possible duplicate of How To Select First Ancestor That Matches A Selector?. May 3, 2012 at 12:15
  • @FelixKling, I was just about to +1 your answer, although not what I needed, I couldn't see a reason for the -1. May 3, 2012 at 12:22
  • I guess because .closest is really the best approach here... but I missed the part in your question that the class .A is actually fixed, so nvm ;) May 3, 2012 at 12:26

5 Answers 5

4
$(".E").click(function(){
    console.log($(this).closest('.A'));
    /* console.log($(this).parents('.A')); works fine too */
});

See
http://api.jquery.com/closest/
http://api.jquery.com/parents/

Note that parent() is different than parents() method (the first one look for one ancestor only)

1
  • 1
    Thank you. I try googling but didn't know what phrase to be searching for. +1 May 3, 2012 at 12:22
3

First Solution:

$(this).closest('.A')

Source: http://api.jquery.com/closest/ This will return the first parent when traversing that matchs the selector.

Second solution:

$(this).parents('.A:first')

Source: http://api.jquery.com/parents/ This will return all the parents that matches the selectors

2

What about

$(this).closest(".A");
1

This is the way i would do it

$(this).parents("div.A")
0

The jQuery parent selector might help you there. You can combine it with the class you are looking for. See the docs @ http://api.jquery.com/parent-selector/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.