Steve
Steve

Reputation: 14912

jQuery Ancestor of nested selector

I have a LI which a bunch of stuff in it

<li class="card">
                <div class="thumb">
                    <img src="/images/adv-ipanema.png" alt="">
                </div>
                <div class="caption">
                    <p class="place">Ipanema Beach</p>
                    <p class="steps">12,000 steps</p>
                </div>
                <div class="buttons">
                    <div class="close"></div>
                    <div class="up"></div>
                    <div class="down"></div>
                </div>
            </li>

What I am trying to do is target the LI itself when the div class "up" is clicked.

I created a simplified proof-of-concept fiddle and was able to use parent().parent() but there must be a better way, no? I tried parentsUntil('li') to no avail, unless I was doing it wrong.

Upvotes: 2

Views: 83

Answers (2)

Ram
Ram

Reputation: 144689

You are looking for closest method:

var listItem = $(this).closest('li');

Upvotes: 2

Marko
Marko

Reputation: 72222

Try closest()

Description
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

i.e.

$(this).closest("li") // or
$(this).closest(".card")

N.B. parentsUntil() will return all the parents up to (but not including) the selector provided

Upvotes: 3

Related Questions