Moving up multiple parents in jQuery - more efficient way?

﹥>﹥吖頭↗ 提交于 2019-11-30 17:42:06

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.

$(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...

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.

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

Senol Kalayci

Try with this code line:

$(this).parent().parent().fadeOut();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!