简体   繁体   中英

Find third parent jQuery

This code works but the triple .parent() feels greasy and I'd like to know if there is a more efficient way of doing this

NOTE

The HTML is repeated multiple times on the page so I have to use classes and (this) in order to animate only the selected item

jquery

$('.view').click(function() {
    $(this).parent().parent().parent().find('.innerContain').animate({ left: '-100%' }, 500); 
});

HTML

<div class="mask">
    <div class="innerContain">
        <!-- Update -->
        <ul class="updateCSI">
            <span class="view">View</span>
        </ul>
        <!-- View -->
        <ul class="viewCSI">
            <span class="update">Update</span>
        </ul>
    </div>
</div>

I think $(this).closest('.innerContain') will do the same.

Live demo (click). (I'm using .hide() for the sake of the demo.)

Why not:

$(this).closest('.innerContain');

In this case closest() will help you to get the first element with class .innerContain whose ancestor of .view element when traverse up the DOM tree.

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