简体   繁体   中英

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

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 eg with find(".test2") .

用这个

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM