Ash Burlaczenko
Ash Burlaczenko

Reputation: 25445

Find the first parent of a selector

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.

Upvotes: 2

Views: 301

Answers (5)

Juan Leung
Juan Leung

Reputation: 356

This is the way i would do it

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

Upvotes: 1

sv_in
sv_in

Reputation: 14049

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

Upvotes: 3

lb1a
lb1a

Reputation: 1

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/

Upvotes: 0

Crab Bucket
Crab Bucket

Reputation: 6277

What about

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

Upvotes: 2

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123387

$(".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)

Upvotes: 4

Related Questions