Moving up multiple parents in jQuery - more efficient way?

前端 未结 6 513
庸人自扰
庸人自扰 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: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.

提交回复
热议问题