Which is more efficient: .parent().parent().parent() ~or~ parents(“.foo”) ~or~ closest(“.foo”)

前端 未结 7 1827
-上瘾入骨i
-上瘾入骨i 2020-12-15 03:06

I have an A tag which triggers the animation of it\'s great-great-great-grandparent. All of the following will work, but which is most efficient, and why?

$         


        
7条回答
  •  难免孤独
    2020-12-15 03:53

    Here’s an analyzation:

    • parent() walks just one level up in the DOM tree.
    • parents(".foo") walks up to the root and selects only those elements that match the given selector .foo.
    • closest(".foo") walks up to the root but stops once an element matches the selector .foo.

    So I would choose the last one, closest(".foo"). The reason:

    • It’s better than chaining parent, because if your document changes because you removed or added one hierarchy, you don’t need to change the jQuery code.
    • It’s better than parents(".foo"), because it stops as soon as a match has been found.

提交回复
热议问题