What's the difference between .closest() and .parents('selector')?

前端 未结 3 1863
囚心锁ツ
囚心锁ツ 2021-02-13 12:41

What\'s the difference between these? Is one more efficient than the other? I\'m a little bit confused to why they both exist. Say I have this markup:



        
3条回答
  •  一整个雨季
    2021-02-13 13:34

    .parent() only goes up one level, while closest() includes the current element, and all parents.

    Example (selecting from the bottom div, x = matched elements):

                 parent()  parent('body')   .closest('div')  .parents('div')
    body     
       div                                                       x
          div       x                                   x
    this-->   div                                x
    

提交回复
热议问题