Moving up multiple parents in jQuery - more efficient way?

前端 未结 6 514
庸人自扰
庸人自扰 2021-01-04 03:06

So, I have a navigation that is a list and has sublists and sublists.

Basically, the nav is by default collapsed, but if people click on a page that\'s in a sublist,

相关标签:
6条回答
  • 2021-01-04 03:11

    If I understand what you're trying to do... you can do something like this:

    // For my benefit, hide all lists except the root items
    $('ul, li', $('#lesson-sidebar ul li')).hide();
    
    // Show active parents and their siblings
    $('li a.active').parents('ul, li').each(function() {
        $(this).siblings().andSelf().show();
    });
    
    // Show the active item and its siblings
    $('li a.active').siblings().andSelf().show();
    

    The parents() and siblings() methods are both great for this kind of thing.

    Edit: There was a bug before where it wasn't showing parent siblings. Try this new version.

    Edit 2: Now it works with class="active" on the anchor instead of the list item.

    0 讨论(0)
  • 2021-01-04 03:12

    $(this).closest("ul") will traverse the parents until it finds a ul

    http://docs.jquery.com/Traversing/closest#expr

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

    0 讨论(0)
  • 2021-01-04 03:14

    Try with this code line:

    $(this).parent().parent().fadeOut();
    
    0 讨论(0)
  • 2021-01-04 03:19

    This will give you the fifth:

    $(this).parents(':eq(4)');
    
    0 讨论(0)
  • 2021-01-04 03:25

    To simplify Lance McNeary's very helpful answer, the trick is to use:

    .parents([selector])
    

    Given a jQuery object that represents a set of DOM elements, the .parents() method allows us to search through the ancestors of these elements in the DOM tree and construct a new jQuery object from the matching elements ordered from immediate parent on up; the elements are returned in order from the closest parent to the outer ones.

    Another user suggested:

    .closest([selector])
    

    Similar to .parents(), this may be a better choice as it stops once it finds the element it is looking for. Seems like it would be more efficient in this case. See http://api.jquery.com/closest/ for more details. Hope this helps people understand the differences between .closest() and .parents() and how powerful and flexible jQuery can be.

    0 讨论(0)
  • 2021-01-04 03:31

    $(this).parents().get()[4] will give you the fifth

    0 讨论(0)
提交回复
热议问题