Anson Aştepta
Anson Aştepta

Reputation: 1143

Jquery:Getting parent's parent

If i have some code like below, a element contains under 3 layers

<span class="dropdown test1">
    <span class="test2" type="button" data-toggle="dropdown">hello</span>
    <ul class="dropdown-menu test3" style="min-width:100px;text-align:centerz-index:999;">
        <li class="CTHK-{{feedId}} test4"  data-url="{{url}}" style="width: 100%; height: 100%;margin-left: 0px !important; margin-top: 0px !important;margin-bottom: 0px !important;"><a href="javascript:void(0)">Btn list</a></li>
        <div class="divider"></div>
    </ul>
</span> 

i want it to console the word "hello" inside class test2

i tried console.log($(this).parent().parent(".test2").text());

i must use this because i am using for loop to genarate datas if i set a consistence class it can't identify which is which

Upvotes: 1

Views: 53

Answers (2)

WBT
WBT

Reputation: 2485

Jquery's .closest(selector) is what you need. Your selector can be ".test2" and you can tack on .text() after selecting the desired element.

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.

Of course, you should make sure your starting point is in fact a descendant of your target point in the data structure you're trying to navigate. In the example given, <span class="test2">hello</span> does not have grandchildren for you to be starting from. You might be going up two levels and then go back down e.g. with find(".test2").

Upvotes: 1

Dinesh J
Dinesh J

Reputation: 113

Use this one

$(this).parent().parent().find(".test2").text();

Upvotes: 1

Related Questions